如何在MATLAB中将单元格数组中不同长度的向量组合成矩阵 [英] How to combine vectors of different length in a cell array into matrix in MATLAB
问题描述
如何有效地将具有不同长度的单元格数组向量组合到一个矩阵中,以0或NaN填充向量至最大长度?对于cell2mat()
,这将是一个不错的选择.
How to efficiently combined cell array vectors with different length into a matrix, filling the vectors to max length with 0s or NaNs? It would be a nice option for cell2mat()
.
例如,如果我有
C = {1:3; 1:5; 1:4};
我想得到其中一个
M = [1 2 3 0 0
1 2 3 4 5
1 2 3 4 0];
或
M = [1 2 3 NaN NaN
1 2 3 4 5
1 2 3 4 NaN];
推荐答案
对于像您这样的 row 个向量的单元格,这将填充带有零的向量以形成矩阵
For a cell of row vectors as in your case, this will pad vectors with zeros to form a matrix
out=cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),C,'UniformOutput',false))
out =
1 2 3 0 0
1 2 3 4 5
1 2 3 4 0
今天早些时候,有人问了一个类似的问题,尽管这个问题是措辞略有不同,我的答案基本上可以满足您的要求.
A similar question was asked earlier today, and although the question was worded slightly differently, my answer basically does what you want.
在此处复制相关部分,可以将不均匀的列向量的单元格零填充到矩阵中,如下所示:
Copying the relevant parts here, a cell of uneven column vectors can be zero padded into a matrix as:
out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),C,'UniformOutput',false));
其中maxLength
被认为是已知的.在您的情况下,您有行向量,对此仅作一点修改.
where maxLength
is assumed to be known. In your case, you have row vectors, which is just a slight modification from this.
如果maxLength
未知,您可以将其获取为
If maxLength
is not known, you can get it as
maxLength=max(cellfun(@(x)numel(x),C));
这篇关于如何在MATLAB中将单元格数组中不同长度的向量组合成矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!