如何在 MATLAB 中将元胞数组中不同长度的向量组合成矩阵

发布于 2024-11-13 05:02:43 字数 335 浏览 3 评论 0原文

如何有效地将不同长度的元胞数组向量组合成一个矩阵,并用 0 或 NaN 将向量填充到最大长度?对于 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];

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().

For example, if I have

C = {1:3; 1:5; 1:4};

I'd like to get either

M = [1 2 3 0 0
     1 2 3 4 5
     1 2 3 4 0];

or

M = [1 2 3 NaN NaN
     1 2 3 4 5
     1 2 3 4 NaN];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风夜微凉 2024-11-20 05:02:43

编辑:

对于您的情况下的向量单元格,这将以零填充向量以形成矩阵

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 今天早些时候提出了类似的问题,尽管问题的措辞略有不同,我的回答基本上满足你的要求。

复制此处的相关部分,不均匀向量的单元可以用零填充到矩阵中,如下所示:

out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),C,'UniformOutput',false));

其中假设maxLength已知。在你的例子中,你有行向量,这只是对此稍加修改。

如果 maxLength 未知,您可以将其获取为

maxLength=max(cellfun(@(x)numel(x),C));

EDIT:

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));

where maxLength is assumed to be known. In your case, you have row vectors, which is just a slight modification from this.

If maxLength is not known, you can get it as

maxLength=max(cellfun(@(x)numel(x),C));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文