Getting all values in the same field for different entries within a structure

41 ビュー (過去 30 日間)
Patrick
Patrick 2023 年 4 月 21 日
編集済み: Stephen23 2023 年 4 月 22 日
Imagine I have a structure of students with certain info and their grades for different modules, looking like:
student(1).grades.math = 7;
student(2).grades.math = 9;
This student list might be any number. Is it possible to get all the different math grades in an array without a for-loop?
mathGrades = student.grades.math;
This doesn't seem to work and gives me the following error:
"Intermediate dot '.' indexing produced a comma-separated list with 2 values, but it must produce a single value when followed by subsequent indexing operations."

採用された回答

Vilém Frynta
Vilém Frynta 2023 年 4 月 21 日
編集済み: Vilém Frynta 2023 年 4 月 21 日
Try arrayfun (use function on the struct to extract the values into the array).
An example on your data:
% Your data
student(1).grades.math = 7;
student(2).grades.math = 9;
student(3).grades.math = 6;
% Use arrayfun to extract all the math grades into vector
mathGrades = arrayfun(@(x) x.grades.math, student)
mathGrades = 1×3
7 9 6
Hope my answer was useful. If it was, I'd be happy if you could accept my answer.

その他の回答 (1 件)

Stephen23
Stephen23 2023 年 4 月 22 日
編集済み: Stephen23 2023 年 4 月 22 日
"Is it possible to get all the different math grades in an array without a for-loop?"
Of course.
The simple and efficient MATLAB approach is to use comma-separated lists:
student(1).grades.math = 7;
student(2).grades.math = 9;
student(3).grades.math = 6;
tmp = [student.grades];
out = [tmp.math]
out = 1×3
7 9 6
Avoid slow ARRAYFUN.

カテゴリ

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