MATLAB: Please help me understand whether I have set up a loop and performed an RMSE (Root Mean Square Error) calculation correctly

arrayfor looplooploopsMATLABrmsesavevariables

I am returning to Matlab after such a long break that I'm essentially a newbie. I'd be very grateful if someone would please help me figure out if I have done what I intend to do!
  • I have a column of data (avgW) from measuring something over time.
  • I have an equation (second line of my code below) to calculate the same thing I measured (wCalc). In the equation, the parameters, a, b, c, d, e, and f are all constants. The parameter "columnOfData" is a column of distinct values.
  • My goal is to find the value of "x" in the equation. What I am trying to do below is first plug in a test value for x (1 – 10000). Then figure out which value (between 1 and 10000) gives me the smallest difference between wCalc and avgW.
I think my method so far would work if "columnOfData" were a constant, but it isn't and I am lost. I'm not even sure what I'm going to end up with when my current calculation finishes. Would anyone happen to know how to find and plot and record the lowest value of RMSE for each value of the column/vector, columnOfData?
Please feel free to comment if there are more appropriate tags for this question. Thank you.
for x = [1:1:10000]
wCalc = ( ( a ./ ( ( columnOfData ./ x ) - b ) ) - c - d - e ) .* f;
RMSE(x) = sqrt( sum( ( wCalc - avgW).^2) ./ g );
end

Best Answer

You could do something like this.
I just made up some numbers to try the code.
Also, obviously variable names like columnOfData are not very meaningful and I wouldn't recommend them but I didn't want to depart to far from your starting point.
I removed some of the ./ and just used / where the operation involved a vector and a scalar so element by element calculations were not needed. Would work with ./ but makes it less clear what you are doing. I also defined x separately from the index in the loop, in case you wanted to use other x values and also so tha you could have an index for recording the RMSE values.
With some more work, you could probably fully vectorize this (eliminate the loop) but at least this should get you started.
% define constants
a = 2.2
b = 3.4
c = 8.1
d = 10.4
e = 0.6
f = 22.4
% define measured value
avgW = [8;7.2;44;3.12]
% define column of data
columnOfData = [3;9;8.3;2]
% number of elements in avgW (and column of data)
g = length(avgW)
x = 1:10000;
for k = 1:10000
wCalc = ( ( a ./ ( ( columnOfData / x(k) ) - b ) ) - c - d - e ) * f; % a vector
RMSE(k) = sqrt( sum( ( wCalc - avgW).^2) / g );
end
% find optimal value, and it's index in the array x
[RMSEOpt,idx] = min(RMSE)
xOpt = x(idx)