필터 지우기
필터 지우기

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