Is there a way to create non-rectangular matrices? For example, if I have a matrix a=[6 8 10]
and another matrix b=[1 5]
, can I vertically concatenate them in order to obtain [6 8 10]
in one row and [1 5]
in another?
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?
来源:https://stackoverflow.com/questions/28332204/how-can-i-concatenate-vectors-to-create-non-rectangular-matrices-in-matlab