Getting array out of for loop

5 次查看(过去 30 天)
Swapnil Rathva
Swapnil Rathva 2020-2-24
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

回答(1 个)

Jesus Sanchez
Jesus Sanchez 2020-2-24
编辑:Jesus Sanchez 2020-2-24
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by