vpasolve and for loop Matlab

1.6k Views Asked by At

I am trying to solve numerically symbolic equation. But one variable in my equation is series of values zv=1:-0.1:0. So, according to my code:

zv=1:-0.1:0
n=length(zv);
j=1:n;
C=15;
eqn=C-64.*(1-zv(j))==0;
R=vpasolve(eqn,x(j),1)

I got mistake in the last row that Index exceeds matrix dimensions.

Other solution which is working is with for loop, but I dont know how to put all solutions (R) in one variable. I got list in my working space where values are changing and it stops when I use all zv terms:

syms x;
for zv=1:-0.1:0
C=15;
eqn=C-64.*(1-zv(j))==0;
R=vpasolve(eqn,x,1)
end
1

There are 1 best solutions below

0
On BEST ANSWER

Regarding your first solution, the 'IndexExceedsMatrixDimension' error is raised by x(j) since x has not been defined. Your current code will also raise a 'ValueError' since you are not passing a numerical function but just a value to the vpasolve function. The following code works by altering the equation like so:

zv = 1:-0.1:0.1;
n  = length(zv);
R  = zeros(1,n);
for j=1:n;
    C=15;
    r=vpasolve(C-64.*(1-zv(j)*x)==0, x, 1);
    R(j)=double(r);
    end
R

Note that the code above is storing the solutions (R) in an array R initialized with R=zeros(1,n). Going with your second solution, you can similarly store the solutions, but you first need to convert the syms to a type that can be stored in an array, e.g., a double. In the code above, you must define zv = 1:-0.1:0.1 to avoid a 'ValueError' in vpasolve, but in the code below you can use zv = 1:-0.1:0. I suggest using warning('off','all') to avoid the potential type conversion warnings.

warning('off','all');
syms x;
zv=1:-0.1:0;
R = zeros(1,length(zv));
for j=1:length(zv),
    C=15;
    R(j)=double(vpasolve(C-64.*(1-x)==0,x,1));
    end
R