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?

- 110,752
- 13
- 76
- 147

- 9
- 5
-
4You can't. MATLAB does not support ragged matrices. One way you could get around this is to make a cell array, where each cell is a vector of unequal lengths. 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];`. – rayryeng Feb 04 '15 at 21:54
1 Answers
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?