Using fsolve in a loop with 2 unknown scalars to solve for each iteration

조회 수: 4 (최근 30일)
Hello,
I would like to solve the couple (a,b) variables in a loop : this way, I would store each solution (a,b) in a vector vec(a) and vec(b) with the size of the number of iterations.
I tried to do :
myfun=@(a,b,i) [
% First equation and Second equation
a^2 + a*b*FISH_sp(i,1:7).*FISH_xc(i,1:7)'+a*b*FISH_xc(i,1:7).*FISH_sp(i,1:7)'+b^2;
a*FISH_sp(i,1:7).*eigenv_sp(1:7,i) + b*FISH_sp(i,1:7).*eigenv_xc(1:7,i) + ...
a*FISH_xc(i,1:7).*eigenv_sp(1:7,i) +...
b*FISH_xc(i,1:7).*eigenv_xc(1:7,i) - (eigenv_sp(i,1:7) + eigenv_xc(i,1:7))*FISH_eigenv_sum(i,i)];
% Solution of system of non linear equations with loop
for i=1:7
a0 = 0.5;
b0 = 0.5;
x0 = [ a0 b0 ];
y(i) = fsolve(@(x)myfun(x(1),x(2),i), x0)
end
with
y(i) that contains each couple (a,b) for each iteration (size(y)= 7x2)
Unfortunately, I get the following error at execution :
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
Error in
compute_solving_Matricial_Equations>@(a,b,i)[a^2+a*b*FISH_sp(i,1:7).*FISH_xc(i,1:7)'+a*b*FISH_xc(i,1:7).*FISH_sp(i,1:7)'+b^2;a*FISH_sp(i,1:7).*eigenv_sp(1:7,i)+b*FISH_sp(i,1:7).*eigenv_xc(1:7,i)+a*FISH_xc(i,1:7).*eigenv_sp(1:7,i),+b*FISH_xc(i,1:7).*eigenv_xc(1:7,i)-(eigenv_sp(i,1:7)+eigenv_xc(i,1:7))*FISH_eigenv_sum(i,i)]
Error in compute_solving_Matricial_Equations>@(x)myfun(x(1),x(2),i)
Error in fsolve (line 230)
fuser = feval(funfcn{3},x,varargin{:});
Error in compute_solving_Matricial_Equations (line 63)
y(i) = fsolve(@(x)myfun(x(1),x(2),i), x0)
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
Anyone could see what's wrong ? I have to check again the size of the matrix I use in my system of equations (there are potential errors since I use transpose operator).
Thanks in advance

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 11월 26일
편집: Ameer Hamza 2020년 11월 26일
That's because fsolve() returns two elements, y(i) can only hold a single element. You can create a matrix where each row store a solution.
y = zeros(7, 2); % pre-allocation for efficient code
a0 = 0.5;
b0 = 0.5;
x0 = [ a0 b0 ];
for i=1:7
y(i, :) = fsolve(@(x)myfun(x(1),x(2),i), x0)
end

추가 답변 (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