How to stop a for loop after comparing one value from an array with another value from another array?
古いコメントを表示
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 件のコメント
Andrei
2022 年 12 月 28 日
Atsushi Ueno
2022 年 12 月 28 日
移動済み: Atsushi Ueno
2022 年 12 月 28 日
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
2022 年 12 月 28 日
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
2022 年 12 月 28 日
> 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
2022 年 12 月 28 日
Jan
2022 年 12 月 28 日
I still do not know, what the wanted result for the data in the question is.
Andrei
2022 年 12 月 28 日
@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
2022 年 12 月 28 日
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Dates and Time についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!