如何使用for循环MATLAB创建矩阵



我有三个大小相同的向量,pressureyearmonth。基本上,我想创建一个压力值矩阵,与使用for循环测量的月份和年份相对应。它应该是12x100,以便显示为从左到右的12个月和100年。

除了创建初始结构之外,我只是不确定如何实际创建矩阵。到目前为止,我多年来只能在一个月内(低于一月份)找到压力。

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

我只能打印出一月份所有年份的压力,但我想将一年中所有月份的所有压力存储在一个矩阵中。如果有人能帮忙,我们将不胜感激。非常感谢。

从变量pressureyearmonth开始。我会做一些类似的事情:

使用for循环的一个相当稳健的解决方案:

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)';

最新更新