【问题标题】:Store individual elements of a matrix into individual elements of a cell in matlab将矩阵的各个元素存储到matlab中单元格的各个元素中
【发布时间】:2014-05-08 06:57:16
【问题描述】:

我在 matlab 中有一个函数,它返回一个大小为 m x n 的矩阵。我想将此矩阵的每个单独元素存储到尺寸为m x n x p x 2 的单元格的单独元素中。这里m,n,p 都是大数,因此我需要一个没有循环的解决方案。

换句话说,我需要一行代码来实现以下循环:

    for k = 1:p
    out = func(parameters(k))  %out is mxn matrix
    for i = 1:m
        for j = 1:n
            cell{i,j,k,1} = out(i,j)
        end
    end
    end

【问题讨论】:

  • 第四维度是什么?
  • 您是否尝试过使用mat2cell
  • @Divakar 我的函数输出两个大小相同的矩阵,我必须将它们都存储在同一个单元格中。因此是第四维
  • @nishantsny,你不能使用cat(4, output1, output2) 连接两个输出吗?或者,mat2cell 方法可以正常工作,您只需要预先分配然后分配如下内容:C{m,n,p,2} = []; C(:,:,:,1) = mat2cell(a, ones(...),...); C(:,:,:,2) = mat2cell(b,....)
  • num2cell 怎么样?第四维中的 2 是从哪里来的?

标签: matlab


【解决方案1】:

我不知道x 2 来自您的m x n x p x 2 输出,但您可以尝试以下操作:

p = 10; n = 15; m = 20;

result = arrayfun(@(x) num2cell( func(x) ), 1:p, 'uni',0);
output = reshape([result{:}],n,m,p);

或:

result = arrayfun(@(x) func(x), 1:p,'uni',0);
output = num2cell(reshape([result{:}],n,m,p));

输出为15 x 20 x 10 x 1 单元格。每个单元格元素都包含一个带有一个数值的“数组”。

如果你坚持,古怪的单线:

output = num2cell(reshape(cell2mat(arrayfun(@(x) func(x),1:p,'uni',0)), n,m,p) );

【讨论】:

  • 它基本上指定了arrayfun 的输入——对于1:p 的每个元素,arrayfun 将其视为x,函数func(x) 被执行。
猜你喜欢
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2013-05-28
  • 2018-07-22
相关资源
最近更新 更多