Convert a cell with structures into a matrix

1 回表示 (過去 30 日間)
Alejandro Fernández
Alejandro Fernández 2021 年 1 月 30 日
編集済み: Stephen23 2021 年 1 月 30 日
Hi, does anyone know how to could I go from the information I have stored in the variable A to what I have in the variable matrix?
% Input data.
A = cell(3,1);
A{1}.data = [1 2 3];
A{1}.a = 0;
A{2}.data = [4 5 6];
A{2}.a = 1;
A{3}.data = [7 8 9];
A{3}.a = 3;
% Result to obtain.
matrix = [1 2 3; 4 5 6; 7 8 9];

回答 (2 件)

David Hill
David Hill 2021 年 1 月 30 日
m=[];
for k=1:3
m=[m;A{k}.data];
end

Stephen23
Stephen23 2021 年 1 月 30 日
編集済み: Stephen23 2021 年 1 月 30 日
Rather than inefficiently storing lots of scalar structures in a cell array, you should just use one efficient non-scalar array, then your task is trivial:
S(1).data = [1 2 3];
S(1).a = 0;
S(2).data = [4 5 6];
S(2).a = 1;
S(3).data = [7 8 9];
S(3).a = 3;
M = vertcat(S.data) % this is all you need!
M = 3×3
1 2 3 4 5 6 7 8 9
Note that you can also convert that unfortunate cell array of scalar structures to one structure array:
S = [A{:}];

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by