简体   繁体   中英

How to create a matrix using a for loop MATLAB

I have three vectors of the same size, pressure , year and month . Basically I would like to create a matrix of pressure values that correspond with the months and years that they were measured using a for loop. It should be 12x100 in order to appear as 12 months going down and 100 years going left to right.

I am just unsure of how to actually create the matrix, besides creating the initial structure. So far I can only find pressure for a single month (below I did January) for all years.

A = zeros([12, 100]);
for some_years = 1900:2000
    press = pressure(year == some_years & month == 1)
end

And I can only print the pressures for January for all years, but I would like to store all pressures for all months of the years in a matrix. If anyone can help it would be greatly appreciated. Thank You.

Starting with variables pressure , year , and month . I would do something like:

A fairly robust solution using for loops:

T = length(pressure); % get number of time periods. I will assume vectors same length
if(length(pressure) ~= T || length(month) ~= T)
   error('length mismatch');
end
min_year = min(year); % this year will correspond to index 1
max_year = max(year); 

A = NaN(max_year - min_year + 1, 12);      % I like to initialize to NaN (not a number)
                                           % this way missing values are NaN
for i=1:T
    year_index = year(i) - min_year + 1;
    month_index = month(i);  % Im assuming months run from 1 to 12
    A(year_index, month_index) = pressure(i);
end

If you're data is SUPER nicely formatted....

If your data has NO missing, duplicate, or out of order year month pairs (ie data is formatted like):

year      month        pressure
1900          1            ...
1900          2            ...
...          ...           ...
1900         12            ...
1901          1            ...
...          ...           ...

Then you could do the ONE liner:

A = reshape(pressure, 12, max(year) - min(year) + 1)';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM