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

21 views (last 30 days)
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?

Accepted Answer

Adam Danz
Adam Danz on 13 Jul 2018
Edited: Adam Danz on 13 Jul 2018
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 Comments
Adam Danz
Adam Danz on 13 Jul 2018
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!