How can I create variable names from dynamic field names?
Show older comments
Hello!
I am fairly new to Matlab so please bear with me. I have been searching for an answer to this question for days to no avail.
I have a piece of code which iterates through subfields of a subfield of a structure and finds the index of the max value of that subfieldfield. I'd like to assign that index to a variable which is named after the subfield of the subfield of the structure.
The structure is called 'session'. The subfield of 'session' is called 'rate'. And the subfield of 'rate' is called 'stim'.
Here's my code:
for names = fieldnames(session.rate)'
MAXrate = session.rate.(names{1}){1:end} == max(session.rate.(names{1}){1:end});
end
Obviously in its current state each iteration of the loop overwrites 'MAXrate'. What I'd really like is to somehow name the variable 'MAXrate' to reflect the subfield of 'rate' from which the index comes. So for example, if
(names{1}) = AUDstim
I'd like to create a variable named
AUDstim_rate
which equals the index produced by
session.rate.(names{1}){1:end} == max(session.rate.(names{1}){1:end});
but it needs to be dynamic so that the next iteration of the loop will produce a variable name that is coherent with the particular subfield of 'rate' that's being iterated through.
I hope this makes sense. Please ask for clarification as needed.
Thanks in advance!
4 Comments
Dhara Yu
on 21 Aug 2018
Correct me if I'm oversimplifying things, but do you simply want to get the name of the item in 'names', and then tack on the name of the corresponding subfield of 'rate'?
Jessica Jacobs
on 21 Aug 2018
@Jessica Jacobs: dynamically naming or accessing variables is one way that beginners force themselves into writing slow, complex, buggy code. Read this to know why:
While it might seem like a good idea, it will make accessing your data harder, slow your code significantly, and make debugging much more difficult. Not only that, but magically naming the variable is not required at all: you can always store the selected data in its own variable, and store the meta-data in another variable:
data = ...
name = ...
And if you make those variables arrays (e.g. cell arrays) then your code can simply and efficiently access them, for any amount of data. Just use indexing (which is simple and efficient) to match the corresponding elements of the data and name arrays.
Jessica Jacobs
on 22 Aug 2018
Accepted Answer
More Answers (0)
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!