How to access elements of all field of structure in same loop
12 views (last 30 days)
Show older comments
Hi,
I defined structure and want to access elements of each feild. I use the below code and it giving error.
%%
close all
clear all
clc
student.name = 'Mekala';
student.age = 2;
student(2).name = 'Punith';
student(2).age = 6;
for i =1:length(student)
name{i} = student{i}.name
end
%% Error: Cell contents reference from a non-cell array object.
for i =1:length(student)
name(i) = student(i).name
end
%% Error: Subscripted assignment dimension mismatch.
for i =1:length(student)
age(i) = student(i).age
end
%% This works.
How to access the all field values in the same loop?
1 Comment
Answers (1)
Ameer Hamza
on 31 May 2020
To access name filed, the following for-loop works
for i =1:length(student)
name{i} = student(i).name
end
However, for-loop is not needed, and there are other easy ways to create an array of all elements of the struct array. Try following code
student.name = 'Mekala';
student.age = 2;
student(2).name = 'Punith';
student(2).age = 6;
name = {student.name};
age = [student.age];
2 Comments
Ameer Hamza
on 31 May 2020
Do you want to automatically create variables with the same name as fields in the structs? If yes, then such practice is highly non-recommended: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. I will create slow and buggy code. If you want to extract all the fields, then I suggest you continue to work with the struct, as the code will be much more efficient and easy to debug.
See Also
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!