How to access elements of all field of structure in same loop
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Ameer Hamza
2020-5-31
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 个评论
Ameer Hamza
2020-5-31
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!