How to stop a for loop after comparing one value from an array with another value from another array?
Mostra commenti meno recenti
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 Commenti
Andrei
il 28 Dic 2022
Atsushi Ueno
il 28 Dic 2022
Spostato: Atsushi Ueno
il 28 Dic 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
il 28 Dic 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
il 28 Dic 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
il 28 Dic 2022
Jan
il 28 Dic 2022
I still do not know, what the wanted result for the data in the question is.
Andrei
il 28 Dic 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
il 28 Dic 2022
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Dates and Time in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!