How to access elements of all field of structure in same loop
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Respuestas (1)
Ameer Hamza
el 31 de Mayo de 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 comentarios
Ameer Hamza
el 31 de Mayo de 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.
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!