使用Matlab将矩阵放到一个空单元格中 [英] put matrices into an empty cell using matlab
问题描述
我有四个2 * 2矩阵,分别称为m1,m2,m3,m4.我想创建一个空的2 * 2单元格数组,它的每个元素也将是2 * 2矩阵.然后我想把m1(1,1)& m2(1,1)& m3(1,1)&将m4(1,1)个元素放入创建的空单元矩阵,以便其中的元素(1,1)为m1(1,1)& m2(1,1)& m3(1,1)& m4(1,1)s.然后再次对我所说的下一个剩余元素进行处理.
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.
有人可以用matlab帮我吗?
Can anyone help me do this with matlab?
推荐答案
您不需要疯狂的任何事情,只需reshape
和num2cell
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.
2015/07/25 14:45
2015/07/25 14:45
根据您的评论,看来您拥有的是一个单元格数组
Based on your comments it seems like what you have is a cell array
M = {m1, m2, ..., mn}
我想你是说每个m是2x2,但是我假设它是q
x r
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}));
因此,进行测试的一种好方法是制作一个M
,然后运行代码
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}));
与上述代码相比,唯一的新作品是cell2mat(cellfun(@(m) m(:), M(:)', 'uni', 0))
.这需要M
(这是矩阵的单元格数组),然后首先将其转换为列向量的单元格数组(通过cellfun
).然后,将这些列连接到一个矩阵中,每一行都是一个m1(i,j), m2(i,j), ...
集.然后像在将每一行拆分成一个单元格数组的其自己的单元格之前一样,然后reshape
使其具有与m
之一相同的大小.
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.
这篇关于使用Matlab将矩阵放到一个空单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!