フィルターのクリア

What is an elegant way to pack and unpack an array of structures to/from a single vector?

41 ビュー (過去 30 日間)
What I've got is an array of structures of somewhat complicated data:
data(1).r = [ 1 2 3 ];
data(1).v = [ 4 5 6 ];
data(1).m = 100;
data(2).r = [ 7 8 9 ];
data(2).v = [ 10 11 12 ];
data(2).m = 101;
I'd like to convert this to an array where each structure was packed together. My solution looks like this:
N = length(data);
x = [];
for i=1:N
x = [ x data(i).r data(i).v data(i).m ];
end
Which results in the correct order that I'd like the structures to be packed into the vector:
x =
1 2 3 4 5 6 100 7 8 9 10 11 12 101
Is there a more elegant way to do that packing, and what is the most elegant way to do the reverse operation and unpack that array back into an array of structures?

回答 (1 件)

madhan ravi
madhan ravi 2019 年 6 月 7 日
編集済み: madhan ravi 2019 年 6 月 7 日
z = struct2cell(data);
x = [z{:}]
data = cell2struct(z,{'r','v','m'}) % reverse
  1 件のコメント
Lamont Granquist
Lamont Granquist 2019 年 6 月 7 日
That is a lot better. But I want data as a function of an arbitrarily modified x vector, so its missing a step which would be the inverse of x = [z{:}]

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by