How to create multiple fields in a structure simultaneously using dynamic field naming
조회 수: 19 (최근 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!