MATLAB Answers

How could I code for loop with this values?

2 views (last 30 days)
Hi guys! I need a simple help from you.
I want to create a for loop with nested if-else condition. Afterthat I want to plot them. Could you guys help me please! I have written the pseudocode below. I need the coding based on this. Please help me out.
Thank you in advance.
%'A' consists some values (e.g. 40, 60, 30, 80, 70, 50, 90, 30);
for A % it will take first 2 values
% 'B' is the maximum value consisting of 2 values from 'A'
% e.g. max (40,60) = 60 then this 60 will be first value of A and last
% value will be 30 so max(60,30) is 60. Afterthat first value is 60 and 2nd value is 80
% so, max(60,80) is 80 likewise.
B = max (A);
% then 'C' is the last value from 'A' which is taken to get the 'B', will be assigned to 'C'.
C = 60; % for 2nd itaration C = 30, for 3rd C = 80, for 4th C = 70, for 5th C = 50 and so on..
% If C reduces 30% of B then,
x = C/10
fprintf ('This is your value %d',x );
else
fprintf ('This is not your value %d',x );
end
end
plot ('x' vs simulation time)

  3 Comments

darova
darova on 21 Feb 2020
Something is wrong in this line
for A(:)
madhan ravi
madhan ravi on 21 Feb 2020
Illustration of expected result would help.
Mohmmad Abu Yousuf
Mohmmad Abu Yousuf on 22 Feb 2020
Thank you,
Result would be like this. Could you please help me Sir.
for 1st iteration:
A is 40 and 60,
so, B is 60,
C is 60 then
if C reduces 30% of B
x = C/10
else
x = C/5
end
for 2nd iteration:
A is 60 and 30,
so, B is 60,
C is 30 then
if C reduces 30% of B
x = C/10
else
x = C/5
end
for 3rd iteration:
A is 60 and 80,
so, B is 80,
C is 80 then
if C reduces 30% of B
x = C/10
else
x = C/5
end
for 4th iteration:
A is 80 and 70,
so, B is 80,
C is 70 then
if C reduces 30% of B
x = C/10
else
x = C/5
end
this will go on till the last value of A

Sign in to comment.

Accepted Answer

darova
darova on 22 Feb 2020
Edited: darova on 23 Feb 2020
This script should give you success you are looking for
A = [40, 60, 30, 80, 70, 50, 90, 30];
B = A(1);
for i = 2:length(A)
B = max(B,A(i));
C = A(i);
if C/B < 0.7
x = C/10;
else
x = C/5;
end
end

  3 Comments

Mohmmad Abu Yousuf
Mohmmad Abu Yousuf on 22 Feb 2020
Thank you very much Sir!
but there has a little problem.
when i = 5 that time 'B' should be 80. because previous maximum value was 80 and now 'A' is 50 so, the maximum value is going to be 80.
I mean at starting it will start from 40 and 60 as there has no value before 40. but after that it will keep the previous maximum value and take another next one value from 'A'.
Sorry to bother you Sir.
darova
darova on 23 Feb 2020
Oh, understand. My bad. I corrected the code. See now

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by