for loop only shows the value of last iterations

Hi everyone, I'm having a problem while using 'for' loop in my coding. Suppose I will get a set of result in 1x12 matrix with a combination of values and empty variable but the results only shows the value of the last iteration. Is it possible if I can obtain and store every values on P1 with respect to its R value for the equation shown in the last line?
Thank you very much for your help.
Po = 101325;
V = 12000;
E = V .* (3.5.*10.^6);
Z = [25 50 100 200 300 400 600 1000 1500 2500 5000 10000];
R = Z / ((E/Po).^(1/3));
for i = min(R):max(R);
if i <= 0.6;
P1 = 0.01;
elseif R <= 7;
P1 = (-0.0014) .* i + 0.01;
else
P1 = [];
end
end
Ps1 = P1 .* Po;

2 Comments

No, a matrix cannot contain an []. For example,
P1=1:5,
P1 = 1×5
1 2 3 4 5
P1(5)=[]
P1 = 1×4
1 2 3 4

Sign in to comment.

 Accepted Answer

Hello Han Xia,
You want P1 to be an array, right? How about this?
Po = 101325;
V = 12000;
E = V .* (3.5.*10.^6);
Z = [25 50 100 200 300 400 600 1000 1500 2500 5000 10000];
R = Z / ((E/Po).^(1/3));
P1=[];
for i = min(R):max(R);
if i <= 0.6;
P1(end+1) = 0.01;
elseif R <= 7;
P1(end+1) = (-0.0014) .* i + 0.01;
else
P1(end+1) = [];
end
end
Ps1 = P1 .* Po;

2 Comments

Thank you sir! I have tried it out and modified a little bit. I think this is the solution to one of my problems.
Regarding the 'for' loop, is there any way I can loop the 12 output R value only? As it is in an irregular pattern, I tried this but still couldn't get it loop within these 12 values.
R = [0.3353 0.6706 1.3412 2.6824 4.0236 5.3467 8.0471 13.4119 20.1178 33.5297 67.0593 134.1186]
for i = 1:length(R)
...
end
You meant something like this:
function foo()
Po = 101325;
V = 12000;
E = V .* (3.5.*10.^6);
Z = [25 50 100 200 300 400 600 1000 1500 2500 5000 10000];
R = Z / ((E/Po).^(1/3));
P1=[];
for i = 1:numel(R)
disp(i)
if R(i) <= 0.6
P1(end+1) = 0.01;
elseif R(i) <= 7
P1(end+1) = (-0.0014) .* i + 0.01;
else
P1(end+1) = 0;
end
end
Ps1 = P1 .* Po;
end

Sign in to comment.

More Answers (1)

Matt J
Matt J on 1 Jul 2021
Edited: Matt J on 1 Jul 2021
Here is what you could do.
I=min(R):max(R);
G=discretize(I,[-inf,0.6,7,inf], 'IncludedEdge','right');
P1=nan(size(I));
P1(G==1)=0.01;
P1(G==2)=(-0.0014) .*I(G==2)+0.01;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Tags

Community Treasure Hunt

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

Start Hunting!