How to generate a loop for vpasolve function
4 次查看(过去 30 天)
显示 更早的评论
I intend to solve a non-transcendental equation using 'vpasolve' for several values of initial guesses.
I do not know how to create a decent loop for this. I tried following code but it does not work:
syms x
y = 1 + cos(x) * cosh(x)
xinitial = linspace(0,30,61);
n = length(xinitial);
for i = 1 : n
R = vpasolve(y == 0, x, xinitial(i))
%R(i,1) = xinitial(i) * 1
end
using R gives values in seperate, and using R(i,1), Matlab does not work.
Do you know how to put the obtained results from vpasolve into a row/columbn matrix?
another interesting point is, it works with 'fzero' function:
f = @(x)1+cos(x)*cosh(x)
xi = linspace(0,10,11)
for i = 1 : length(xi)
A(i,1) = fzero(f,xi(i))
end
I don't know why it does not work with vpasolve function (I mean the looping step)
Thanks a lot
1 个评论
Peter O
2020-3-11
Alireza,
As you've noted, R gets overwritten on each pass of the loop. Unfortunately I don't have the symbolic math toolbox so I can't test your code exactly, but the indexing should work since x is a scalar. In the code you posted, you're assigning the initial guess to R instead of the solved value. Perhaps this is the issue?
Try this. I've preallocated R prior to the loop (a bit more efficient). It should give you a column vector of symbolic variables matching the (row) vector of xinitial.
syms x
y = 1 + cos(x) * cosh(x)
xinitial = linspace(0,30,61);
n = length(xinitial);
R = sym('0',[n,2])
for i = 1 : n
R(i,1) = vpasolve(y == 0, x, xinitial(i))
end
回答(1 个)
Walter Roberson
2020-3-11
R(i, 2) = vpasolve(y == 0, x, xinitial(i));
R(i,1) = xinitial(i);
Or you could
R = arrayfun(@(xi) vpasolve(y==0,x,xi), xinitial) ;
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!