如何在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 类似的问题今天早些时候被问到,尽管问题是措辞略有不同,我的答案基本上满足您的需求.
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屋!