如何在 MATLAB 中将不同长度的单元累积到矩阵中?
所以,我有一个由不同长度的 1xN 向量组成的元胞数组。我想将它们附加到一个矩阵中,以便我可以使用 imagesc
显示它们。显然矩阵必须是最大向量的宽度。我当前的代码如下:
tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []};
lens = cellfun('length', tcell);
rmat = NaN(length(tcell), max(lens));
for i = 1:length(tcell)
rmat(i, 1:lens(i)) = tcell{i};
end
有谁知道此类问题的矢量化解决方案?由于 MATLAB 的 JIT,我并不真正担心这个循环的速度。我只是想扩展我的知识,这是我在编程中经常遇到的情况。
So, I have a cell-array of 1xN vectors of different lengths. I want to append them into a matrix so I can display them with imagesc
. Obviously the matrix must be the width of the largest vector. My current code for this is below:
tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []};
lens = cellfun('length', tcell);
rmat = NaN(length(tcell), max(lens));
for i = 1:length(tcell)
rmat(i, 1:lens(i)) = tcell{i};
end
Does anyone know a vectorized solution for this type of problem? I'm not really worried about the speed of this loop because of MATLAB's JIT. I'm just trying to expand my knowledge and this is a case that I come across quite often in my programming.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种使用
cellfun
的解决方案匿名函数 首先用NaN
值,然后vertcat
将单元格内容放入矩阵中:输出:
Here's one solution that uses
cellfun
with an anonymous function to first pad each cell withNaN
values, thenvertcat
to put the cell contents into a matrix:And the output: