How can I concatenate vectors to create non-rectangular matrices in MATLAB?

折月煮酒 提交于 2019-12-02 09:04:14
rayryeng

The direct answer is no. MATLAB does not support ragged or non-rectangular or non-square matrices. One way you could get around this is to make a cell array, where each cell is a vector of unequal lengths.

Something like:

a = [6 8 10];
b = [1 5];
c = cell(1,2);
c{1} = a;
c{2} = b;

celldisp(c)

c{1} =

     6     8    10

c{2} =

     1     5

Another way would be to create a matrix where those values that contain nothing get mapped to a preset number, like zero. Therefore, you could concatenate a and b to be a matrix such that it becomes [6 8 10; 1 5 0];. If this is what you prefer, you can do something like this:

a = [6 8 10];
b = [1 5];
c = zeros(2, 3);
c(1,1:numel(a)) = a;
c(2,1:numel(b)) = b;
disp(c)

 6     8    10
 1     5     0

A more comprehensive treatise on this particular topic can be found in gnovice's answer: How can I accumulate cells of different lengths into a matrix in MATLAB?

Another related answer was created by Jonas: How do I combine uneven matrices into a single matrix?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!