dt1 dt2 dt3 dt
1 3 6 10
2 4 1 5
3 6 5 3
4 7 4 1
5 1 2 4
6 2 8
7 8
8
9
10
我有上述数据,我想将它们合并到一个矩阵 (10 x 4) 中。最大行数为 10。我创建了一个 zeros
矩阵。但是,我遇到了一个问题,因为数据的维度不同。如何获得如下输出?我是否应该对数据进行排序并将缺失值替换为 0?
1 1 1 1
2 2 2 0
3 3 0 3
4 4 4 4
5 0 5 5
6 6 6 0
7 7 0 0
8 8 8 0
9 0 0 0
10 0 0 10
最佳答案
这里是 @gnovice 的修改版本对先前类似问题的回答
%# group the variables. If you would be generating them in a loop, you could use the loop
%# to group them, i.e. have something like
%# for i=1:n
%# dtCell{i} = "function that generates dt_i"
%# end
dtCell = {dt1,dt2,dt3,dt};
nCells = length(dtCell);
maxVal = max(cellfun(@max,dtCell)); %# this way, I don't have to know vector orientation
%# you could replace the loop with calls to cellfun.
%# While this may make you feel more Matlab-ish, it wouldn't be
%# faster, or more readable
out = zeros(maxVal,nCells);
for iCell = 1:nCells
idx = dtCell{iCell}; %# this assignment is just for clarity
out(idx,iCell) = idx;
end
关于matlab - 如何将不均匀矩阵组合成单个矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3174631/