How do I get each array produced by a for loop iteration to be added as a different column in matrix?

2 visualizaciones (últimos 30 días)
I have a for loop that goes through the years 2000–2020 and picks out the temperature and datenum value for each day in the specified year. The temperature is stored in an array, p1, and the datenums are stored in an array, p2. p1 and p2 have different values with each loop iteration/each year, and I'd like to store those yearly values as columns in a matrix (olTempMatrix for temperatures and olDateMatrix for datenums). The problem I'm having with my for loop is that it only stores the values for the final year (2020), rather than storing each year in its own column, so my two matrices end up with the same set of values in every column.
My code is reproduced below, and the file with olDateNums and olYears is attached so you can reproduce my results.
There must be a simple change I can make here to get my matrices to have each column fill with the data from each different year... but Im stuck! Thanks in advance for the help.
[olYr,olMo,olDay] = datevec(olDateNums);
olTempMatrix = NaN(365,21,'single');
olDateMatrix = NaN(365,21,'single');
for olYears = 2000:2020
p = find(olYr == olYears);
p1 = olTemps(p) %this produces an array of daily avg temp for each year
p2 = olDateNums(p) %this produces an array of datenums for each year
for columns = 1:21 %Make each array into one column of a matrix
olTempMatrix(:,columns) = p1;
olDateMatrix(:,columns) = p2;
end
end
olTempMatrix
olDateMatrix

Respuesta aceptada

Scott MacKenzie
Scott MacKenzie el 25 de Jun. de 2021
This should work:
k = 1;
for olYears = 2000:2020
p = find(olYr == olYears);
p1 = olTemps(p) %this produces an array of daily avg temp for each year
p2 = olDateNums(p) %this produces an array of datenums for each year
olTempMatrix(:,k) = p1;
olDateMatrix(:,k) = p2;
k = k + 1;
end

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by