Getting array out of for loop

5 views (last 30 days)
Swapnil Rathva
Swapnil Rathva on 24 Feb 2020
Edited: Jesus Sanchez on 24 Feb 2020
Hello,
I am trying to run a for loop for fixed amount of iteration for variable n and wanna get output variables in one array so that i can have a graph.
but every time I am getting updated value out of loop and all previous values are gone.
Please help me find code that can save array instead of last partivular updated value. My code is as follows;
clc
clear
%% pre-defined variables and equations
p_in = 100;
p_out = 30000;
cr = p_out/p_in;
n = 1;
cr_stage = (p_out/p_in)^(1/n);
%% alghorithm
while cr_stage > 3.99 % cr_stage variable should not exceed 4, otherwise increment in variable n
n(n) = n+1;
cr_stage(n) = (p_out/p_in).^(1./n);
if cr_stage(n) < 3.99 % when its below 4, loop breaks itself.
break
end
end
n_1 = 1;
n = [n_1, n];
cr_stage = cr_stage(end);
stages = numel(n);
for i = n(1):n(end) % for loop for iteration of n times
p_out = p_in * cr_stage % want this variable output in array to have graph
p_in = p_out; % updated value of variable above given.
end

Answers (1)

Jesus Sanchez
Jesus Sanchez on 24 Feb 2020
Edited: Jesus Sanchez on 24 Feb 2020
Treat p_out as a vector and you will be fine:
for i = 1:length(n) % for loop for iteration of n times
p_out(i) = p_in * cr_stage % want this variable output in array to have graph
p_in = p_out(i); % updated value of variable above given.
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!