How to create multiple fields in a structure simultaneously using dynamic field naming

18 ビュー (過去 30 日間)
I have a cell array of n field names associated with a double array of m x n numerical data. I would like to pack these into one structure with n fields that each access an m x 1 array of numerical data.
So far I have only been able to do this in a for loop:
fieldnames = {'name1';'name2';'name3';'name4'}; % cell array of n field names
data = rand(396,4); % m x n double array of data
for i = 1:length(fieldnames)
struct.(fieldnames{i}) = data(:,i);
end
This gives me the result I want, but there must be some clever way to do this without resorting to a for loop, right? Any ideas?

採用された回答

Adam Danz
Adam Danz 2018 年 7 月 13 日
編集済み: Adam Danz 2018 年 7 月 13 日
Good news and bad news.
Good news, here's (kind of) what you want in one line of code.
S = cell2struct(num2cell(data), fieldnames, 2);
Bad news, is that S is a structure array whereas your 'struct' is a structure. If you want to access the first field in your variable,
struct.name1
If you want to access the first field of my variable,
[S.name1]'
These are identical vectors but since mine is a structure array, the syntax differs.
[ UPDATE, thanks to Walter Roberson's suggestion] Here's what you want in 1 line of code and in the format you need.
S = cell2struct(num2cell(data,1), fieldnames, 2);
  5 件のコメント
Adam Danz
Adam Danz 2018 年 7 月 13 日
Yes! Libby, I updated my answer at the bottom and added the two critical characters that Walter suggested and now that solution works. Thanks, Walter - I had a feeling I was missing something.
Libby Jones
Libby Jones 2018 年 7 月 13 日
Super slick, thank you both!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by