Filter löschen
Filter löschen

For Loop to Cycle through Struct

8 Ansichten (letzte 30 Tage)
Nat Person
Nat Person am 13 Jan. 2021
Beantwortet: Arjun am 20 Aug. 2024 um 6:18
I have a 6x1 struct and want to create a for loop that will cycle through and pull out the name field of the 1x1 struct.
How can I do that? ** I am using R2012a **
I apologize for the strange format, the toolbar at the top of the body is missing and I'm still trying to fix it.
  2 Kommentare
Athrey Ranjith Krishnanunni
Athrey Ranjith Krishnanunni am 15 Jan. 2021
You probably don't need a for loop, you can use the function fieldnames(S) (look at its documentation for more info).
P. S. You can use Alt + Enter to switch between code and plain text modes.
AANJANEY KUMAR VERMA
AANJANEY KUMAR VERMA am 25 Jul. 2022
listNames = { YourStructArray.Name };
This will return a cell array of all the names present in the array of structs.
Hope this helps

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Arjun
Arjun am 20 Aug. 2024 um 6:18
Hi,
As per my understanding, there is a struct array of dimension 6x1 and you want to use a 'for' loop to cycle through each and pick a certain field.
This can be done using the below mentioned steps:.
  • Initialize a cell array to store the vested fields
  • Loop through each element of the struct array
  • Access the name field using .(dot) operator and store it in the cell array for future use
Please see the below code on how to achieve this:
% Create a 6x1 structure array with a 'name' field
myStruct(1).name = 'Alice';
myStruct(2).name = 'Bob';
myStruct(3).name = 'Charlie';
myStruct(4).name = 'David';
myStruct(5).name = 'Eve';
myStruct(6).name = 'Frank';
% Initialize a cell array to store the names
names = cell(length(myStruct), 1);
% Loop through each element of the structure array
for i = 1:length(myStruct)
% Access the 'name' field of each element
names{i} = myStruct(i).name;
end
% Display the names
disp(names);
The provided code is a sample script that demonstrates how to display the name fields from all the structures within a structure array. You can adjust this code to fit your specific requirements.
I hope this will help!

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by