Trouble with a for loop: Index exceeds the number of array elements (31)

Hello, I am a beginner with matlab and am having trouble with a for loop. I want to create a vector by pulling data from a data set. The data set is divided into four columns (year, month, day, temperature). I want to take the temperature data for July from 1997 to 1999 and put it into a vector. This is what I have so far
for y = 1997:1999
save = temp(temp(:,1) == y & temp(:,2) == 7,4);
samp = save(y);
end
I keep getting this error Index exceeds the number of array elements (31). I understand what the error is telling me, but I do not know how to fix it. I attached the data set file.

 Respuesta aceptada

save = temp(temp(:,1) == y & temp(:,2) == 7,4);
That already extracts the 4th column of all matching rows -- nothing will be put into save unless the first column of temp matches.
samp = save(y);
y is like 1997. save is just the fourth column of the rows that matched. It is not likely that you had at least 1997 matches.
I would suggest to you that save already contains the data you want.
However... you are throwing it away immediately after you extract it: the next iteration of the loop would overwrite save
If you are sure that you will get exactly the same number of entries each time, write the data into a 2D array. If you are not sure that you will get exactly the same number of entries each time, write the data to a cell array.
Also, we recommand against using save as the name of a variable, as that will interfere with using save as a command . And it will confuse readers who expect save to be a command.

3 comentarios

Hi Walter,
I know the data is equal for each entry, so I think a 2D array is the way to go. I am still having trouble with that though. This is one of the new things I tried, but it still gives only the last iteration.
samp = zeros(31,3);
for y = 1997:1999
samp = temp(temp(:,1) == y & temp(:,2) == 7,4);
end
How do a write the data into the 2D array properly in order to save the three iterations?
samp = zeros(31,3);
for y = 1:3
samp(:,y) = temp(temp(:,1) == y+1997-1 & temp(:,2) == 7,4);
end
Thank you it worked!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 12 de Sept. de 2020

Comentada:

el 12 de Sept. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by