Problem nested for loop - using break

3 visualizzazioni (ultimi 30 giorni)
Rob
Rob il 12 Feb 2022
Commentato: Rob il 12 Feb 2022
Hi everyone, I have the following problem for the nested loops shown in the example code below.
The idea is that when the computed value is greater than 10, then there is no need to continue the jj loop with more computations. Hence, once the value exceeds 10, exit the jj loop and start again from the next iteration in the kk loop.
For example, let's say kk=1 and jj =1, and the computed value is greater than 10, then exit the jj loop and start from kk = 2. Again, compute the value for jj =1,2,3... and exit whenever the value is greater than 10, and so on. However, if the value is below 10 store the value in a matrix of zeros, which was set outside the loop.
Problem is, when I checked the store_matrix after the code has finished, all entries are zero. However, I know some values are smaller than 10 and they are not stored in the matrix. I have to mention that the computed values can sometimes be NaN, so I am not sure if this causes the problem.
I checked various posts regarding how to use the break command for nested loops, but I still couldn't figure out the answer. Am I using the break command correctly? Many thanks in advance for your help!
Rob
for kk = 1:length(XX)
K_X = XX(kk) ; % XX/YY are set outside the loop
K_Y = YY(kk) ;
for jj = 1:length(PP)
value = PP(jj) + BB(jj) + K_X + K_Y; %This is just an example computation; PP, BB are vectors set outside the loops
if value < 10
store_matrix(jj,kk) = value ; %store value in an output matrix, which is defined outside the loops
elseif value > 10
break
end
end
end

Risposta accettata

Image Analyst
Image Analyst il 12 Feb 2022
Modificato: Image Analyst il 12 Feb 2022
It looks like it should work. Try printing out value right after you assign it to check its value. And make sure you have an else. You can replace your elseif with an else.
fprintf('kk = %d. jj = %d. value = %f\n', kk, jj, value);
if value < 10
fprintf('Assigning row %d, column %d of store_matrix.\n', jj, kk)
store_matrix(jj,kk) = value ; %store value in an output matrix, which is defined outside the loops
else
fprintf('Value too big. Breaking out of jj loop.\n')
break
end
It's alright if some of the values are nan. The array can store nan's. However any unassigned values (because they were skipped) will appear as zero.
If that doesn't work please supply us with XX, YY, PP and BB so we can try some things.
  1 Commento
Rob
Rob il 12 Feb 2022
Hi @Image Analyst, many thanks for your prompt response! The display option helps a lot. I just saw it stored the values. Thanks again for your help. Rob

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by