# Need some clarification

1 view (last 30 days)
Alex on 17 Feb 2012
Edited: may on 15 Oct 2013
Hey all, I've got some code that's trying to solve a system of 6 equations using fsolve. It runs a loop, because the six equations represent variables in a data set, so multiple iterations are desired. Here is the code itself:
%data.csv should be defined as the file with measured values.
assert (mod(size(data, 1), 6) == 0, ...
'Input data must have an integer multiple of 6 rows');
assert (size(data, 2) == 2, ...
'Input data must have exactly two columns.');
nsys = size(data, 1) / 6;
soln = zeros(nsys, 6);
options=optimset('MaxFunEvals',1e10,'MaxIter',25000);
for k = 1 : nsys,
F = c_generate(data(6*(k-1) + (1:6), 1:end));
guess = [1 1 1 1 1 1];
soln(k, :) = fsolve(F, guess,options);
end
fid=fopen('results.csv','w');
fprintf(fid,'%5.5f, %5.5f, %5.5f, %5.5f, %5.5f, %5.5f\n',soln);
fclose(fid);
And here is the function file:
function F = c_generate(data)
assert (ndims(data) ==2, ...
'System parameters ''p'' must be 2D matrix.');
assert (all(size(data) ==[6,2]), ...
'System parameters must be 6-by-2 matrix.');
y = data(:,1);
n = data(:,2);
F = @(x) (x(1)+(x(2).*(y.^2))+(x(3)/(y.^2))+(x(4)/(y.^4))+(x(5)/(y.^6))+(x(6)/(y.^8))-n.^2);
end
When I run it, I get an error:
??? Error using ==> plus
Matrix dimensions must agree.
Error in ==>
c_generate>@(x)(x(1)+(x(2).*(y.^2))+(x(3)/(y.^2))+(x(4)/(y.^4))+(x(5)/(y.^6))+(x(6)/(y.^8))-n.^2)
at 9
F = @(x)
(x(1)+(x(2).*(y.^2))+(x(3)/(y.^2))+(x(4)/(y.^4))+(x(5)/(y.^6))+(x(6)/(y.^8))-n.^2);
Which leads to the usual red cascade. Since I'm using the skeleton of an older function file to create this new one, I don't know what it means by matrix sizes must agree. Since the x's are being solved for, don't they represent 1x1 matrices? How should I fix this, what does this mean?

Matt Tearle on 17 Feb 2012
Just from looking at the code, it looks as though you're dividing a scalar by a column vector:
y = data(:,1);
...
...x(3)/(y.^2)...
This will result in a matrix right-divide, which will return a row vector. But
x(2).*(y.^2)
will give a column vector. And adding these together, of course, gives our good friend "Matrix dimensions must agree".
I suspect you want to do ./ instead of /.
##### 2 CommentsShowHide 1 older comment
Matt Tearle on 17 Feb 2012
Heh. I once spent a couple of hours trying to debug an algorithm because I had * instead of .* Total n00b move, even after more years of MATLAB than I care to remember.