Within a function, I convert a cell array C_in to a numeric array A_in:
A_in = cell2mat(C_in);
I then perform calculations on A_in that will result in A_out with the same size as A_in. In the end, I need to convert the numeric array A_out to a cell array C_out, with the sizes of C_out being exactly the same as C_in. I know that mat2cell is used for this, but I was wondering if there is a straight-forward way to have mat2cell figure out the row and column distances automatically based on C_in. C_in is expected to have a size of {[1, n1], [1, n2], [1, n3], ...} or {[n1, 1], [n2, 1], [n3, 1], ...}, and my function should produce a C_out with identical dimensions in both cases.

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 11 月 10 日

0 投票

cellsizes = cellfun(@size, C_in);
C_r = cellfun(@(M) M(1), cellsizes);
C_c = cellfun(@(M) M(2), cellsizes);
mat2cell(A_out, C_r, C_c)

3 件のコメント

the cyclist
the cyclist 2017 年 11 月 10 日
This solution did not work for me:
C_in = {[1 2],[1 2 3]};
A_in = 2 * cell2mat(C_in);
A_out = 2*A_in;
cellsizes = cellfun(@size, C_in,'UniformOutput',false); % Had to add the additional arguments due to non-scalar output.
C_r = cellfun(@(M) M(1), cellsizes);
C_c = cellfun(@(M) M(2), cellsizes);
mat2cell(A_out, C_r, C_c)
The last line gives the error
Input arguments, D1 through D2, must sum to each dimension of the input matrix size, [1 5].
That line is actually trying to create a cell array of dimensions {[1 2],[1 3];[1 2],[1 3]}.
I don't see a good fix right off the top of my head, so just posting my observation.
hmalissa
hmalissa 2017 年 11 月 10 日
The problem with the example above (which is very close to my application, since I'm dealing with C_in with similar shape) is that C_r is [1 1], but mat2cell requires '1' instead. I found that 'unique' produces the correct output:
C_out = mat2cell(A_out, unique(C_r), unique(C_c));
Thanks for your help! I'm just surprised that there isn't a built-in implementation of this.
Walter Roberson
Walter Roberson 2017 年 11 月 10 日
cellsizes = cellfun(@size, C_in, 'Uniform', 0);
if size(A_in,2) == 1
C_r = cellfun(@(M) M(1), cellsizes);
C_c = 1;
else
C_r = 1;
C_c = cellfun(@(M) M(2), cellsizes);
end
C_out = mat2cell(A_out, C_r, C_c);

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

質問済み:

2017 年 11 月 10 日

コメント済み:

2017 年 11 月 10 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by