Search code examples
matlabmatrixconcatenationcell-array

Concatenate matrices out of a cell in Matlab


I wrote a simple matlab test code where I store 3 matrices (a,b,c) inside of a cell (D). I then create a vector of indexes (idx) so I am able to selected only the first and third matrix out of the cell. The code is presented below:

% Begin code %
a = [0 1; 2 3];        % matrix a
b = [4 5];             % matrix b
c = [5 6; 7 8; 9 10];  % matrix c

D = cell(3,1);         % Initialize cell D
D{1,1} = a; D{2,1} = b; D{3,1} = c; % Copy matrices inside cell

idx = [1 3]'; % Indexes vector

D = D(idx); % select matrix a and c from D
% End code (Solution should start from here...) %

if I display D{:,1} what I get is

ans =

     0     1
     2     3

ans =

     5     6
     7     8
     9    10

My goal is to concatenate the 2 matrices (a,b) out of the cell D in a smart way (using some specific built in matlab function) and possibly avoiding for loop; This is what I want:

E = [0    1
     2    3
     5    6
     7    8
     9   10];

the solution should be the most elegant possible but I am open to any suggestion. The only constrain should be not to change the code I presented, since the solution should be a continuation of what I have written.

NOTICE: Since what I am trying to do should work with an undefined number of matrices (in this example I have only 3 but the could be also 1000), solutions like E = [D{1,:};D{2,1}] are not accepted.


Solution

  • Answer to my question found here:

    cat(1,D{:})