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

23 ビュー (過去 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 Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by