I have four 2*2 matrices called m1,m2,m3,m4. I want to create an empty 2*2 cell array which every element of it will be also 2*2 matrices. Then I want to put m1(1,1) & m2(1,1) & m3(1,1) & m4(1,1) elements into that created empty cell matrices so that element (1,1) of them will be that m1(1,1) & m2(1,1) & m3(1,1) & m4(1,1) s. And again do it again for next remaind elements as I said.
Can anyone help me do this with matlab?
You don't need anything crazy, just reshape
and num2cell
c = reshape(num2cell([m1(:), m2(:), m3(:), m4(:)], 2), size(m1));
I think this is a good general way to do it.
Edit: 2015/07/25 14:45
Based on your comments it seems like what you have is a cell array
M = {m1, m2, ..., mn}
I think you're saying that each m is 2x2, but I'll assume it's q
xr
And you want to get it in the form,
c = {[m1(1,1), m2(1,1), ..., mn(1,1)], [m1(1,2), m2(1,2), ..., mn(1,2)], ..., [m1(1,q), m1(1,q), ..., mn(1,q)]
[m1(2,1), m2(2,1), ..., mn(2,1)], [m1(2,2), m2(2,2), ..., mn(2,2)], ..., [m1(2,q), m1(2,q), ..., mn(2,q)]
...
[m1(r,1), m2(r,1), ..., mn(r,1)], [m1(r,2), m2(r,2), ..., mn(r,2)], ..., [m1(r,q), m1(r,q), ..., mn(r,q)]}
If all this is accurate, then the code you need is
c = reshape(num2cell(cell2mat(cellfun(@(m) m(:), M(:)', 'uni', 0)), 2), size(M{1}));
So a good way to test this is to make a M
, then run the code
M = arrayfun(@(i) randi(100, 7, 3), 1:14, 'uni', 0);
c = reshape(num2cell(cell2mat(cellfun(@(m) m(:), M(:)', 'uni', 0)), 2), size(M{1}));
the only new piece compared to the above code is the cell2mat(cellfun(@(m) m(:), M(:)', 'uni', 0))
. This takes M
(which is a cell array of matrices) and first turns it into a cell array of column vectors (by the cellfun
). It then concatenates those columns into a matrix which each row is a m1(i,j), m2(i,j), ...
set. Then like before we split each row into its own cell of a cell array, then reshape
it so it's the same size as one of the m
's.