Need some clarification

2 次查看(过去 30 天)
Alex
Alex 2012-2-17
编辑: may 2013-10-15
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.
data = csvread('data_c.csv');
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
Matt Tearle 2012-2-17
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 个评论
Alex
Alex 2012-2-17
Ha, perfect! I can't believe I forgot the (.). Wow, always pays to have someone watching your back.
Thanks!
Matt Tearle
Matt Tearle 2012-2-17
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by