naming a structure

clear all
FName = {'Data1','Data2','Data3'};
data1 = [rand(32,1),rand(32,1),rand(32,1)];
NewName = {'Location1'};
Location1 = struct('Data1',data1)
From this example how is it possible to adapt the script so that instead of typing 'Location1' as the name of the structure, can that be defined from 'NewName' i.e. defining the name of the structure from a pre-defined string?

 Risposta accettata

Kevin Holst
Kevin Holst il 22 Feb 2012

2 voti

You can use eval, but eval needs to be used with extreme care. You can really screw things up accidentally.
eval([NewName ' = struct(''Data1'',data1);'])
If somehow your string is a command like 'clear all' or worse then that command will be run, so use eval sparingly. If there's a possibility of that happening then you might want to put a check in there.

1 Commento

Jan
Jan il 23 Feb 2012
Creating variables dynamically has two big disadvantages: 1. The debugging is very hard, because you cannot see in the code, where the value is defined. 2. Inserting a variable to the internal lookup-table of variables is slow, while variables, which are defined explicitely in the code are handled much faster, e.g. by the JIT-acceleration.

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 22 Feb 2012

2 voti

4 Commenti

Richard
Richard il 23 Feb 2012
apologies if I missed this, but from the following example (given with the link):
names = {'fred' 'sam' 'al'};
for ind = 1:length(names)
s.(names{ind}) = magic(length(names{ind}));
end
Is it also possible to have different structure names within the loop, so say that if s was pre defined in a string, such as
SName = {'s'};
Would it then be possible to name the structure according to this?
Walter Roberson
Walter Roberson il 23 Feb 2012
Don't do that. Use a master structure name and put your dynamic names all at a level underneath that.
Richard
Richard il 23 Feb 2012
Well I'm trying to think of a way to create 4 structures, as in if SNanme would be {'loc1','loc2','loc3','loc4'}. I'm thinking I have to create a structure for each because each of these locations has the same measured variable therefore if they are all in the workspace at the same time they will over write one another. So are you suggesting to make 4 structures within one master structure?
Kevin Holst
Kevin Holst il 23 Feb 2012
I like this approach, and will be suggesting it in the future. Much safer, clearer, and cleaner.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements 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!

Translated by