登录论坛

查看完整版本 : 如何在MATLAB中将不同长度的单元格累积到矩阵中?


poster
2019-12-10, 20:41
因此,我有一个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,我并不真正担心此循环的速度。我只是想扩展自己的知识,这是我在编程中经常遇到的一个案例。



回答:

这是一个使用带有匿名函数的 (https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html) cellfun (https://www.mathworks.com/help/matlab/ref/cellfun.html)的解决方案,首先用NaN (https://www.mathworks.com/help/matlab/ref/nan.html)值填充每个单元格,然后使用vertcat (https://www.mathworks.com/help/matlab/ref/vertcat.html)将单元格内容放入矩阵中:

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

更多&回答... (https://stackoverflow.com/questions/3054437)