这一员额是在前一个关于调整矩阵表的问题之后提出的:
下面的例子说明了我面临的另一个问题:
depth = [0:1:20]';
data = rand(1,length(depth))';
d = [depth,data];
d = [d;d(1:20,:);d];
在这里,我想修改这个矩阵,这样每一列代表一个特定的深度,每一行代表时间,因此最终我将有3行(即天)和21列(即每个深度的度量)。然而,我们不能重塑这一点,因为某一天的测量数是不一样的,即有些是缺失的。这一点已为下列人士所知:
dd = sortrows(d,1);
for i = 1:length(depth);
e(i) = length(dd(dd(:,1)==depth(i),:));
end
从“e”中我们发现,不同的日子,深度的数量是不同的。我如何在矩阵中插入一个nan,使每一天都有相同的深度值?首先,我可以找到独特的深度:
如果某一天缺少一个深度(来自唯一的),我想将深度插入到正确的位置,并将nan插入到数据列中的相应位置。如何才能做到这一点?
发布于 2012-10-26 03:04:03
你刚才正确地认为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
你可能想要转置矩阵。
发布于 2012-10-26 02:59:08
从你的问题中还不完全清楚你的数据到底是什么样子,但下面这些可能会帮助你找到答案。
假设你有一个列向量
day1 = 1:21';
而且,最初,所有的值都是NaN
day1(:) = NaN
接下来假设您有一个2d度量数组,其中第一列表示深度,第二列表示深度。例如
msrmnts = [1,2;2,3;4,5;6,7] % etc
然后分配
day1(msrmnts(:,1)) = msrmnts(:,2)
将只在day1
的那些行中设置值,这些行的索引位于msrmnts
的第一列中。第二个语句使用Matlab将一个数组用作另一个数组中的一组索引的功能,例如
d(9 7 8 12 4) = 1:5
将元素[9 7 8 12 4]
of d
设置为值1:5
。注意,元素的索引不需要按顺序排列。您甚至可以在索引数组中多次插入相同的值,例如[4 4 5 6 3 4]
,尽管它并不十分有用。
https://stackoverflow.com/questions/13085382
复制