[英]How to create a matrix using a for loop MATLAB
我有三個大小, pressure
, year
和month
相同的向量。 基本上,我想創建一個壓力值矩陣,該矩陣與使用for循環測量的月份和年份相對應。 它應為12x100
,以顯示12個月下降和100年左右變化。
除了創建初始結構外,我不確定如何實際創建矩陣。 到目前為止,我只能找到所有年份中一個月的壓力(低於一月份的情況)。
A = zeros([12, 100]);
for some_years = 1900:2000
press = pressure(year == some_years & month == 1)
end
而且我只能打印所有年份一月份的壓力,但我想將矩陣中所有年份所有月份的所有壓力存儲起來。 如果有人可以幫助,將不勝感激。 謝謝。
從變量pressure
, year
和month
。 我會做類似的事情:
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
如果您的數據沒有丟失,重復或順序不正確的年月對(即數據格式如下):
year month pressure
1900 1 ...
1900 2 ...
... ... ...
1900 12 ...
1901 1 ...
... ... ...
然后,您可以做一個內膽:
A = reshape(pressure, 12, max(year) - min(year) + 1)';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.