Using fsolve in a loop with 2 unknown scalars to solve for each iteration
3 次查看(过去 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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!