# Storing values from for-loop into a matrix

1 view (last 30 days)
Rami Abdelhadi on 21 Apr 2022
Commented: KSSV on 22 Apr 2022
Hello, this is my first time using MATLAB. I only have very limited experience using VBA and that has been years since. I have a project for a class, and I can't seem to store my data in a matrix. I am calculating values in a for-loop but cannot increment through the matrix (namely, M_isentropic) since my increment is not an integer. I've found that multivariable for-loops are not an option in MATLAB. Any solution for this? Thanks
p.s. I originally found this code online and have been trying to tweak it to make it work for my incremental situation.
increment = length/0.01;
V = nan(1,increment);
T = nan(1,increment);
ARatio_Inc = nan(1,increment);
M_isentropic = nan(1,increment);
% Set up the solver
for i = 0.00001:0.01:length
length_Inc = 0 + i;
h_exit_Inc = 2.0*(tan(theta_t) * length_Inc+0.5*h_throat);
ARatio_Inc = h_exit_Inc / h_throat;
problem.objective = @(Msup) (1/Msup^2)*(((2+gm1*Msup^2)/gp1)^(gp1/gm1))-ARatio_Inc^2;
problem.solver = 'fzero';
problem.options = optimset(@fzero);
% Solve supersonic root
problem.x0 = [1+1e-6 50];
M_isentropic(1,i) = fzero(problem);
% Print solutions to command window
% fprintf('==== MATLAB SOLVER ====\n');
% fprintf('Msup: %3.4f\n',M_isentropic);
% fprintf('=======================\n\n');
% The calculated temperature at each M_isentropic.
T(1,i) = ((1 + M_isentropic(1,i)^2 * (gamma-1)/2)^-1)*T_stag;
% The calculated velocities at each M_isentropic
V(1,i) = M_isentropic(1,i)*sqrt(gamma*287.058*T(1,i));
end
disp(M_isentropic)

KSSV on 21 Apr 2022
Edited: KSSV on 21 Apr 2022
In MATLAB array indices should be posititve integers, in the given code, i the loop index is used as index in T, V; i is not an integer and it will throw error. So change the code as shown below:
increment = length/0.01;
V = nan(1,increment);
T = nan(1,increment);
ARatio_Inc = nan(1,increment);
M_isentropic = nan(1,increment);
% Set up the solver
count = 0 ;
for i = 0.00001:0.01:length
count = count+1 ;
length_Inc = 0 + i;
h_exit_Inc = 2.0*(tan(theta_t) * length_Inc+0.5*h_throat);
ARatio_Inc = h_exit_Inc / h_throat;
problem.objective = @(Msup) (1/Msup^2)*(((2+gm1*Msup^2)/gp1)^(gp1/gm1))-ARatio_Inc^2;
problem.solver = 'fzero';
problem.options = optimset(@fzero);
% Solve supersonic root
problem.x0 = [1+1e-6 50];
M_isentropic(1,i) = fzero(problem);
% Print solutions to command window
% fprintf('==== MATLAB SOLVER ====\n');
% fprintf('Msup: %3.4f\n',M_isentropic);
% fprintf('=======================\n\n');
% The calculated temperature at each M_isentropic.
T(1,count) = ((1 + M_isentropic(1,i)^2 * (gamma-1)/2)^-1)*T_stag;
% The calculated velocities at each M_isentropic
V(1,count) = M_isentropic(1,i)*sqrt(gamma*287.058*T(1,count));
end
disp(M_isentropic)
##### 2 CommentsShowHide 1 older comment
KSSV on 22 Apr 2022
Thanks is accepting/ voting the answer. :)