For Loop for Non-Consecutive Values in an Array...

15 visualizaciones (últimos 30 días)
Michelle De Luna
Michelle De Luna el 7 de Feb. de 2020
Comentada: Michelle De Luna el 7 de Feb. de 2020
Hi everyone! I had a question regarding for loops when your "i" values are not consecutive.
I have a large matrix with thousands of timesteps. From this matrix, I need to find those index values where the date includes a specific month like December. I have been able to create a variable that includes the index value of all of those specifically selected timesteps quite easily, however the next step of my code includes a for loop where I use these index value to produce an image.
So, for example, my variable "December" is an array with timestep values like: 1745, 1767, 2918, 3958, 5938, and thousands more in random order.
How do I create a for loop that uses the specific timestep value (e.g. 1745 or 2918)? Would the "length" option do the trick? Any help would be greatly appreciated.
dec = find(dates.Month == 12)
for i = 1:length(dec)
i
end

Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de Feb. de 2020
for i = dec
disp([i,dates(i).Month])
end
This might be enough for your situation. However, it is very common to need to have one output for each non-consecutive input. In such a case, you should learn this kind of pattern:
decvals = find etc
numdec = length(decvals);
outputs = zeros(numdec, 1);
for decidx = 1 : numdec
dec = decvals(decidx);
do something with dec
outputs(decidx) = whatever;
end
In this kind of pattern, decvals does not need to be consecutive or integer or unique -- it does not even need to be real-valued or numeric. This kind of pattern will loop through all of whatever values are there, extracting one at a time (here into the variable dec) and storing the output computed into the location corresponding to the offset into the array of values.
  1 comentario
Michelle De Luna
Michelle De Luna el 7 de Feb. de 2020
Thank you for your help, Walter! Very well explained. Super helpful.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by