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

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

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

Ah, interesting. I think for my purposes I would rather have for loops in the beginning and not have to use brackets when working with the data later on, since I have lots of data but not so many types (structures). I was wondering whether I had missed something obvious.
Thanks!
I agree that it will be much more convenient to use the for loop and a simple structure. If the structure array in my example could be converted to a structure that would be helpful but I don't know if that's possible.
num2cell(data, 1) to split by column and then it should end up like you want.
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

Community Treasure Hunt

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

Start Hunting!