How to convert a cell to matrix?

3 ビュー (過去 30 日間)
SM
SM 2020 年 7 月 16 日
編集済み: the cyclist 2020 年 7 月 16 日
Example:
A={[1 3 4];
[2 5 6 4];
[2 6 8 9 5 6];
[3 6 5 4 1]}
I know it is not possible by using
B=cell2mat(A);
as it has different array size.
We may use NaN to follow concatenation rules.
How can I do that?
Once converted to matrix, How can I come back to same cell from the matrix?
  2 件のコメント
the cyclist
the cyclist 2020 年 7 月 16 日
For that input A, what exactly do you want the output to be? For example, do you want
B=[1 3 4 NaN NaN NaN;
2 5 6 4 NaN NaN;
2 6 8 9 5 6;
3 6 5 4 1 NaN]
?
SM
SM 2020 年 7 月 16 日
Yes, First i want what you have written. Second, I want to come back from B to A.

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

採用された回答

Akira Agata
Akira Agata 2020 年 7 月 16 日
編集済み: Akira Agata 2020 年 7 月 16 日
How about the following way?
% Convert to numeric array
maxLen = max(cellfun(@numel,A));
A = cellfun(@(x)[x, NaN(1,maxLen - numel(x))],A,'UniformOutput',false);
B = cell2mat(A);
% Back to cell array
A2 = mat2cell(B,ones(1,size(B,1)));
A2 = cellfun(@rmmissing,A2,'UniformOutput',false);

その他の回答 (1 件)

the cyclist
the cyclist 2020 年 7 月 16 日
編集済み: the cyclist 2020 年 7 月 16 日
Here is one straightforward way:
% Original data
A={[1 3 4];
[2 5 6 4];
[2 6 8 9 5 6];
[3 6 5 4 1]};
%%%%%% Convert to B
% Get number of rows of A, and the maximum vector length within A
M = numel(A);
N = max(cellfun(@numel,A));
% Preallocate B to the correct size
B = nan(M,N);
% Fill each row of B with the corresponding row of A
for im = 1:M
Arow = A{im};
B(im,1:numel(Arow)) = Arow;
end
%%%%%% Convert B back to A
% Preallocate A2 to the correct number of rows
M2 = size(B,1);
A2 = cell(M2,1);
% Fill A2 with the non-NaN elements of B
for im = 1:M2
A2{im} = B(im,~isnan(B(im,:)))
end
% Show that they're identical
isequal(A,A2)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by