MATLAB: Store whileloop vector values in a matrix

matrixwhile loop

I want to store output 'steadystate' (a column vector) as a matrix as steadystate(1), steadystate(2),steadystate(3), steadystate(4).
I have not posted my whole code. Initial gues councoutGuess=[0.1;0.1;0.1;0.1] initial steadystate values = [ 0.1504734, -0.049281077, 0.14977213, 0.34987724]
while abs(steadystate-concoutGuess)>0.0000001 %Convergence error criteria for the Newton Rhapson loop
bigmatrix=alt_bigmatrix; %Using the stored symbolic matrix for the loop calculations
concoutGuess=steadystate; %Updating values
concout=steadystate;
fA= ((flowinA*concinA-flowout*concout(1))/Vol) - k1*concout(1)*concout(2); %Recalcualting values similar to previous calculations
fB= ((flowinB*concinB-flowout*concout(2))/Vol) - k1*concout(1)*concout(2) - k2*concout(2)*concout(3);
fC= ((-flowout*concout(3))/Vol) + k1*concout(1)*concout(2) - k2*concout(2)*concout(3);
fD= ((-flowout*concout(4))/Vol) + k1*concout(2)*concout(3);
molflow = [ fA; fB; fC; fD ];
bigmatrix= subs(bigmatrix); %Substituting updated values and calculating in symbolic form
differential=inv(bigmatrix);
differential=vpa(differential,8);%Evaluating symbolic and rounding to specified significant figures
molflow=vpa(molflow,8);
steadystate = concoutGuess - (differential*molflow); %Newton Rhapson formula for steady state
i=i+1;
steadystate = vpa(steadystate,8);
end

Best Answer

You can use save the values in a matrix as given in the code below
count = 1;
steadyStateMatrix = []
while your_condition
% your code goes here
steadyStateMatrix(:, count) = steadystate; % steadystate is a column vector
count = count + 1;
end
This will give you a steadyStateMatrix matrix, in which each column contain next iteration of steadystate.
The above code will solve your problem. However, note that steadyStateMatrix is initialized as
steadyStateMatrix = [];
this will make your code very slow if while loop has several iterations. To avoid this inefficiency, initialize your matrix, with a proper number of columns e.g.
m = #; % define m equal to number of element in 'steadystate'
steadyStateMatrix = zeros(m, 100); % 100 is a failrly large number of iterations, this will speed up your code
and add the following after end of while loop
if size(steadyStateMatrix, 2) > count
steadyStateMatrix(:, count+1:end) = [];
end