create a while loop with varying conditions.

2 views (last 30 days)
Fidele Adanvo
Fidele Adanvo on 16 Oct 2020
Commented: Sindar on 17 Oct 2020
How can I make a while script capable of performing the following task:
A = [A1 A2 A3 .............. An]
B an abitrary value
1. Compare with (whlile) A1 com B
if true, update the value of A1 (code) and re-compare (While) with the updated value of A1 in 2 (second iteration)..
If false, store A1, stay in the routine for the next one, which would be A2, and remove A1 from the rest of the comparisons to be made (end operation with A1).
2. Compare (While) with the new value of A1 with B (In case the first itinerary was true) and A2 with B.
if the comparison of A1 with B is true, update the value of A1 and re-compare (While) with the updated value of A1 in 3 (second iteration)..
IF the comparison of A1 with B is false, store A1 stay in the routine for the next one, which would be A3, and remove A1 from the rest of the comparisons to be made (end operation with A1).
if the comparison of A2 with B is true, update the value of A2 and re-compare (While) with the updated value of A2 in 3 (second iteration).
IF the comparison of A2 with B is false, store A2 stay in the routine for the next one, which would be A3, and remove A2from the rest of the comparisons to be made (end operation with A2).
The process continues until it reaches the last element of A
  3 Comments
Fidele Adanvo
Fidele Adanvo on 17 Oct 2020
answering your question
1-The value of B is fixed. For example B = 10.
2-The compassion of Ai/ B is simple for example Ai <= 10
3-The comparison always starts with the first element of vector A. Example A1 <= 10
4-A=1:1:10; i=1;
while A(1,i)<10
i=i+1;
if i>10
break
end
A(1,i)=2; % Compare again A(1,i) and A(1,(i+1)) so on until i=10
end
Sindar
Sindar on 17 Oct 2020
That doesn't really answer questions 3-6, but I'll give it a go:
% create an A vector, and a B for comparison
A=1:10;
B = 10;
% find locations where Ai<=B
idx = A<=B;
% update these locations to be 2
A(idx) = 2;
% find locations where new Ai<B
idx = A<=B;
% update these locations to be 3
A(idx) = 3;
or, if you want to continue through to 10:
% create an A vector, and a B for comparison
A=1:10;
B = 10;
for ind=2:10
% find locations where Ai<=B
idx = A<=B;
% update these locations to be ind (2, 3, ..., 10)
A(idx) = ind;
end
if you only want to update the first Ai less than B:
% create an A vector, and a B for comparison
A=1:10;
B = 10;
% find first where Ai<=B
idx = find(A<B,1,'first');
% update this location to be 2
A(idx) = 2;
Does that help?

Sign in to comment.

Answers (0)

Categories

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

Tags

Products

Community Treasure Hunt

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

Start Hunting!