Create a new structure using a function in a for loop.

1 view (last 30 days)
I have a structure, and I want to use the values of one of the fields as the names of new structures. So, for instance, I have structure "struct" with the field "field" that has the following values that are strings:
I have a function whose output is a new structure that I want to be the name of the field values in my first structure (so, value1, value2, and value3) and whose input I also want to be the name of the field values in my first structure. I'm trying to create the new structures (named value1, value2, and value 3 using a for loop like this
for j = 1 length(struct.field)
[struct.field{j}] = function(struc.field{j})
The error I'm getting is
Dot indexing is not supported for variables of this type.
Other than the for loop portion, my function works as long as I manually specify the new structure name. I'm trying to avoid manually specifying the new structure name if possible.
Can I create new structures using a function in a for loop like what I've been trying? If so, what do I need to do to fix my method?
Stephen23 on 12 May 2022
Edited: Stephen23 on 12 May 2022
"The second link shows how to generate field names from variables."
"Is the second link the preferred approach..."
"preferred": maybe. Dynamic fieldnames might be quite a suitable approach... or perhaps not. Or perhaps a table... Or a cell array... Or an ND array. It depends very much on your data (e.g. sizes, types, how they are structured, etc), what processing you will do on them, etc.
In general fieldnames (just like variable names) should not contain meta-data (your 'value1', 'value2', etc. are probably meta-data). Meta-data should be stored in a variable, not in its name. Perhaps a structure array might be a good choice for storing that data:
S(1).data = [..];
S(1).name = 'value1';
S(2).data = [..];
S(2).name = 'value2';
"or just about showing how to dynamically name variables, which is bad practice?"
Generating fieldnames from variables has nothing (directly) to do with dynamic variable names. Fields are not variables.

Sign in to comment.

Answers (0)


Find more on Structures 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!

Translated by