How to access a field of a struct by indexing?
Mostra commenti meno recenti
I have a 1-by-1 struct that possesses 3 fields named B, C, and D. Is there any way to call D by its index (i.e., D is the third field of struct A, so call the third field of struct A without mentioning the field name D) rather than its name (i.e, A.D)?
A.B = 1;
A.C = 2;
A.D = 3;
1 Commento
@Rightia Rollmann: you might like to consider using a non-scalar structure, which lets you use indexing to access structures:
Risposta accettata
Più risposte (1)
Guillaume
il 26 Feb 2017
Yes, there is a way to get the nth field directly:
fns = fieldnames(A);
A.(fns{3})
But be aware that the order of the fields depends solely on the order in which they were created. As Jan pointed out, two structures may be indentical, yet have different field order.
Usually, you would only access fields by their index when you're doing some structure metaprogramming
5 Commenti
Eric Mink
il 5 Ott 2018
This is the correct answer. Further elaborated in order to change all fields:
for n = 1:numel(fieldnames(tempanchors))
names = fieldnames(tempanchors)
tempanchors.(names{n}).status = 1
end
This snippet takes a struct `tempanchors` and adds a field status with value 1 to every field of tempanchors.
James Richard
il 14 Dic 2019
@Eric Mink why do you need to add new field, "status" = 1?
James Richard
il 14 Dic 2019
Modificato: James Richard
il 15 Dic 2019
@Guillaume, how do you make it shorter, one line only?
I mean something like this
A.(fieldnames(A){3}) % it doesn't work
%Error:
%Indexing with parentheses '()' must appear as the last operation of a valid indexing expression.
Edit, I found the solution from stackoverflow
A.(subsref(fieldnames(A),substruct('{}',{3})))
Vaishnavi
il 19 Dic 2023
To add on to this question, can someone explain why A.(subsref(fieldnames(A),substruct('{}',{:}))) would not work?
@Vaishnavi: One reason that doesn't work is that you need single quotes around the colon in substruct. But even then, it may not do what you expect. Here's what it does (gets the value of the first field of A):
A = struct('field1',1,'field2',2)
A.(subsref(fieldnames(A),substruct('{}',{':'})))
In order to know whether that "works", one would need to know what you expected it to do.
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!