How to stop a for loop after comparing one value from an array with another value from another array?
Show older comments
c_year = [0 2 3 4 6 7 8 10];
l_year = [1 5 9];
count = 1188;
statement = true ;
for j = 1:length(l_year)
for i =1:length(c_year)
if c_year(i) >l_year(j)
count = count - j;
break
end
end
end
I want the loop to stop when the value in c_year is bigger than the value in l_year (e.g. stop when c_year value is 2 and l_year value is 1 and then take away 1 from count, or when c_year value is 6 and l_year value is 5 and take away 2 from count (because it is the 2nd value in l_year) or compare 10 and 9 and take away 3 from counter, I assume you get the idea).
Any suggestions how this can be done?
Also, sorry for the bad explanation, but I could not find a better way to explain the problem. Hope it is clear enough.
13 Comments
Andrei
on 28 Dec 2022
Atsushi Ueno
on 28 Dec 2022
Moved: Atsushi Ueno
on 28 Dec 2022
How about reducing the nested loops?
c_year = [0 2 3 4 6 7 8 10];
l_year = [1 5 9];
count = 1188;
for j = 1:length(l_year)
if find(c_year > l_year(j),1)
count = count - j;
break; % stop the loop
end
end
Rik
on 28 Dec 2022
What do you mean 'they contain further code which needs to be executed'? The point of stopping a loop is not to execute further code. What exactly do you want to achieve?
Or do you need something like continue?
Andrei
on 28 Dec 2022
> but will it work for comparing value 6 in c_year and value 2 in l_year and subtract 2 from count?
Yes it does, by removing the break sentence. Would you really want to stop the for loop? You might need continue as @Rik told you.
c_year = [0 2 3 4 6 7 8 10]; l_year = [1 5 9];
count = 1188;
for j = 1:length(l_year)
if find(c_year > l_year(j),1)
count = count - j;
sprintf('j = %d, count - j = %d', j, count)
end
end
@Andrei: What is the wanted output? I still do not understand, what you want to achieve.
A bold guess:
c_year = [0 2 3 4 6 7 8 10];
l_year = [1 5 9];
count = 1188;
a = (c_year > l_year.') .* (1:numel(c_year))
result = count - cumsum(a(a~=0))
Andrei
on 28 Dec 2022
Jan
on 28 Dec 2022
I still do not know, what the wanted result for the data in the question is.
Andrei
on 28 Dec 2022
@Andrei: Again: If the input is
c_year = [0 2 3 4 6 7 8 10];
l_year = [1 5 9];
count = 1188;
what is the wanted result for count? It is a number, isn't it?
The explanation "maximum value in 'data'" is not useful, because there is no variable called data and it is not mention, that maximum of what is wanted.
Andrei
on 28 Dec 2022
Accepted Answer
More Answers (0)
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!