如何将不同长度的单元格累积到 MATLAB 中的矩阵中? [英] How can I accumulate cells of different lengths into a matrix in MATLAB?
问题描述
所以,我有一个由不同长度的 1xN 向量组成的元胞数组.我想将它们附加到一个矩阵中,以便我可以用 imagesc
显示它们.显然矩阵必须是最大向量的宽度.我目前的代码如下:
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
有人知道此类问题的矢量化解决方案吗?由于 MATLAB 的 JIT,我并不真正担心这个循环的速度.我只是想扩展我的知识,这是我在编程中经常遇到的一个案例.
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.
推荐答案
这是一个使用 cellfun
带有 匿名函数 首先用 NaN 填充每个单元格
值,然后 vertcat
将单元格内容放入矩阵中:
Here's one solution that uses cellfun
with an anonymous function to first pad each cell with NaN
values, then vertcat
to put the cell contents into a matrix:
tcell = {[1 2 3], [1 2 3 4 5], [1 2 3 4 5 6], [1], []}; % Sample cell array
maxSize = max(cellfun(@numel, tcell)); % Get the maximum vector size
fcn = @(x) [x nan(1, maxSize-numel(x))]; % Create an anonymous function
rmat = cellfun(fcn, tcell, 'UniformOutput', false); % Pad each cell with NaNs
rmat = vertcat(rmat{:}); % Vertically concatenate cells
和输出:
rmat =
1 2 3 NaN NaN NaN
1 2 3 4 5 NaN
1 2 3 4 5 6
1 NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN
这篇关于如何将不同长度的单元格累积到 MATLAB 中的矩阵中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!