How to create multiple fields in a structure simultaneously using dynamic field naming
21 次查看(过去 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?
0 个评论
采纳的回答
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!