MATLAB: Using while loop to run through equation n times using column matrix of n rows

matrixwhile loop

I am trying to obtain a column matrix of n rows that has the solution of an equation done n times. This equation has other variables in it that also are column matrices of n rows. Basically, I have an equation that has matrices in it. I am trying to solve the equation a number of times equal to the rows in the column matrices and get a matrix answer of the variable I am solving for, if that makes sense. Here is what I have so far but am unable to obtain the matrix of the variable I am solving for in the equation:
syms beta cp2 lambda2
c1= 0.5176;
c2= 116;
c3= 0.4;
c4= 5;
c5= 21;
c6= 0.0068;
l= (1/(lambda2+0.008*beta))-(0.035/((beta^3)+1));
solve(cp2==c1*(c2*l-c3*beta-c4)*exp(-c5*l)+c6, beta);
lambda_m = [7.943485689; 7.876168014; 7.809981728; 7.744898547; 7.680891121;
...
7.876168014; 7.943485689];
cp_m = [0.3862077656; 0.3764718995; 0.3670605433; 0.3579602882; 0.3491583852;
...
0.3764718995; 0.3862077656];
beta_m=zeros(67,1);
i=1;
while i<=67
cp2=cp_m(i,:)
lambda2=lambda_m(i,:)
R=solve(cp2==c1*(c2*l-c3*beta-c4)*exp(-c5*l)+c6, beta)
%beta_m(i,:)=R
i=i+1
end

Best Answer

I would not use the Symbolic Math Toolbox for iterative numerical calculations. It is inefficient for that purpose.

I would use fzero and anonymous function implementations of ‘l’ and the expression you want to solve for in the loop (that I call ‘fcn’ here):

c1= 0.5176;
c2= 116;
c3= 0.4;
c4= 5;
c5= 21;
c6= 0.0068;
l = @(beta,lambda2) (1/(lambda2+0.008*beta))-(0.035/((beta^3)+1));                  % Create Anonymous Function
lambda_m = [7.943485689; 7.876168014; 7.809981728; 7.744898547; 7.680891121; 
    ...
    7.876168014; 7.943485689];
cp_m = [0.3862077656; 0.3764718995; 0.3670605433; 0.3579602882; 0.3491583852;
    ...
    0.3764718995; 0.3862077656];
beta_m=zeros(67,1);
i=1;
while i<=67 
    cp2=cp_m(i,:);
    lambda2=lambda_m(i,:); 
    fcn = @(beta) (c1*(c2*l(beta,lambda2)-c3*beta-c4)*exp(-c5*l(beta,lambda2))+c6) - cp2;
    R(i) = fzero(fcn, 1)
    i=i+1
end

Experiment to get the result you want.