Matlab 如何将不均匀矩阵组合成单个矩阵?
我有上面的数据,我想在一个单一的矩阵(10 x 4)组合。最大行数为10。我创建了一个Matlab 如何将不均匀矩阵组合成单个矩阵?,matlab,matrix,Matlab,Matrix,我有上面的数据,我想在一个单一的矩阵(10 x 4)组合。最大行数为10。我创建了一个zeros矩阵。但是,我有一个问题,因为数据没有相同的维度。如何获得以下输出?我应该对数据进行排序并用0替换缺少的值吗 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 下面是对之前类似问题的答案的修改版本 1 1 1
zeros
矩阵。但是,我有一个问题,因为数据没有相同的维度。如何获得以下输出?我应该对数据进行排序并用0替换缺少的值吗
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
下面是对之前类似问题的答案的修改版本
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
让我们定义示例数据:
%# 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
一种方法是创建一个遮罩,然后在遮罩指示的位置填充值:
dt1 = randi(10,10,1)-1;
dt2 = randi(10,7,1)-1;
dt3 = randi(10,6,1)-1;
dt4 = randi(10,5,1)-1; %// example data. Column vectors.
示例结果(随机数据):
可能的副本。你需要做的就是首先将变量分组到一个单元格数组中。我还有一个问题,变量的数量是递增的,例如,在一个循环中,我如何对它进行分组?哎呀,看起来这是类似的,但与我链接的问题没有完全重复。抱歉,很好,但是您需要将最大值的计算更改为类似于
maxVal=max(vertcat(dtCell{:}))
获取所有单元格的最大值。@gnovice:谢谢提醒!现在修好了。
dt = {dt1, dt2, dt3, dt4}; %// collect data into a cell array
n = cellfun(@numel, dt); %// length of each vector
mask = bsxfun(@le, (1:max(n)).', n); %// create mask
result = zeros(size(mask)); %// initiallize result with zeros
result(mask) = vertcat(dt{:}); %// fill in values.
result =
2 3 2 7
3 9 8 6
4 7 9 0
4 3 5 7
2 1 1 1
1 7 7 0
8 0 0 0
1 0 0 0
7 0 0 0
8 0 0 0