Getting array out of for loop

조회 수: 5 (최근 30일)
Swapnil Rathva
Swapnil Rathva 2020년 2월 24일
편집: Jesus Sanchez 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