在matlab中用nan值重新格式化矩阵

Kat*_*tyB 1 matlab matrix

这篇文章是关于矩阵重组的前一个问题:

在matlab中重新格式化矩阵

以下示例演示了我面临的另一个问题:

depth = [0:1:20]';
data = rand(1,length(depth))';
d = [depth,data];
d = [d;d(1:20,:);d];
Run Code Online (Sandbox Code Playgroud)

在这里,我想改变这个矩阵,以便每列代表一个特定的深度,每行代表时间,所以最终我将有3行(即天)和21列(即每个深度的测量).但是,我们无法重塑这一点,因为给定日期的测量数量不同,即有些缺失.这是众所周知的:

dd = sortrows(d,1);
for i = 1:length(depth);
    e(i) = length(dd(dd(:,1)==depth(i),:));
end
Run Code Online (Sandbox Code Playgroud)

从'e'我们发现不同日期的深度数是不同的.如何在矩阵中插入一个nan,以便每天都有相同的深度值?我首先可以找到独特的深度:

unique(d(:,1))从此,如果某一天缺少深度(来自唯一),我想将深度插入正确的位置,并将nan插入数据列中的相应位置.怎么能实现这一目标?

ang*_*nor 5

你正确地想,这unique可能会派上用场.您还需要第三个输出参数,它将唯一深度映射到原始d矢量中的位置.看看这段代码 - 评论解释了我的所作所为

% find unique depths and their mapping onto the d array
[depths, ~, j] = unique(d(:,1));

% find the start of every day of measurements
% the assumption here is that the depths for each day are in increasing order 
days_data = [1; diff(d(:,1))<0];

% count the number of days
ndays = sum(days_data);

% map every entry in d to the correct day
days_data = cumsum(days_data);

% construct the output array full of nans
dd = nan(numel(depths), ndays);

% assing the existing measurements using linear indices
% Where data does not exist, NaN will remain
dd(sub2ind(size(dd), j, days_data)) = d(:,2)

dd =

0.5115    0.5115    0.5115
0.8194    0.8194    0.8194
0.5803    0.5803    0.5803
0.9404    0.9404    0.9404
0.3269    0.3269    0.3269
0.8546    0.8546    0.8546
0.7854    0.7854    0.7854
0.8086    0.8086    0.8086
0.5485    0.5485    0.5485
0.0663    0.0663    0.0663
0.8422    0.8422    0.8422
0.7958    0.7958    0.7958
0.1347    0.1347    0.1347
0.8326    0.8326    0.8326
0.3549    0.3549    0.3549
0.9585    0.9585    0.9585
0.1125    0.1125    0.1125
0.8541    0.8541    0.8541
0.9872    0.9872    0.9872
0.2892    0.2892    0.2892
0.4692       NaN    0.4692
Run Code Online (Sandbox Code Playgroud)

您可能想要转置矩阵.