How to access elements of all field of structure in same loop

조회 수: 12 (최근 30일)
Mekala balaji
Mekala balaji 2020년 5월 31일
댓글: Stephen23 2020년 5월 31일
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개)

Ameer Hamza
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
Mekala balaji
Mekala balaji 2020년 5월 31일
for loop is for a big structure, can't we access all the fields in same loop?
Ameer Hamza
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by