Naming a struct with a variable?

56 Ansichten (letzte 30 Tage)
Saar Peles
Saar Peles am 18 Mär. 2020
Bearbeitet: Voss am 30 Okt. 2024
Hi, I'm trying to sort some data into a struct by having a specific part of the struct name be variable. I have a mapping function that designates the name based on the index. This is a simplified version of what I'm trying to code:
AHAmap = [ 6 9 2 17]
S10.AHAmap(3) = 66;
My expectation being that the struct S10.2 equals 66 (or even better S10.AHA3 = 66. I've been stuck for a while so help is appreciated!
  1 Kommentar
Adam Danz
Adam Danz am 18 Mär. 2020
Bearbeitet: Adam Danz am 18 Mär. 2020
"...by having a specific part of the struct name be variable"
Are you looking for a way to name the variable S10 dynamically?
This is not recommended. Avoid using dynamic variable names to name a structure at all cost. Here are reasons why.
If you're naming the fields, that's a different story (see Steven Lord's answer).

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Steven Lord
Steven Lord am 18 Mär. 2020
2 isn't a valid struct array field name. But you can do something like your second alternative using dynamic field names.
S = struct();
FN = "apple" + 2 + "c"
S.(FN) = 42 % equivalent to S.apple2c = 42
Search the documentation for "dynamic field names" for more information.
  1 Kommentar
Saar Peles
Saar Peles am 18 Mär. 2020
Bearbeitet: Voss am 30 Okt. 2024
Holy [redacted], I think you've saved me. I appreciate the help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by