2

I have created a structure containing a few different fields. The fields contain data from a number of different subjects/participants.

At the beginning of the script I prompt the user to enter the "Subject number" like so:

 prompt='Enter the subject number in the format SUB_n: ';
 SUB=input(prompt,'s');

Example SUB_34 for the 34th subject.

I want to then name my structure such that it contains this string... i.e. I want the name of my structure to be SUB_34, e.g. SUB_34.field1. But I don't know how to do this.

I know that you can assign strings to a specific field name for example for structure S if I want field1 to be called z then

S=struct;
field1='z';
S.(field1);

works but it does not work for the structure name.

Can anyone help?

Thanks

Suever
  • 64,497
  • 14
  • 82
  • 101
Maheen Siddiqui
  • 539
  • 8
  • 19
  • one option would be using `eval` although is not a good programming practice: `eval([SUB ' = struct'])` will create a struct variable whose name is the content of SUB. –  Jul 19 '16 at 15:09

1 Answers1

7

Rather than creating structures named SUB_34 I would strongly recommend just using an array of structures instead and having the user simply input the subject number.

number = input('Subject Number')
S(number) = data_struct

Then you could simply find it again using:

subject = S(number);

If you really insist on it, you could use the method proposed in the comment by @Sembei using eval to get the struct. You really should not do this though

S = eval([SUB, ';']);

Or to set the structure

eval([SUB, ' = mydata;']);

One (of many) reasons not to do this is that I could enter the following at your prompt:

>> prompt = 'Enter the subject number in the format SUB_n: ';
>> SUB = input(prompt, 's');
>> eval([SUB, ' = mydata;']);

And I enter:

clear all; SUB_34

This would have the unforeseen consequence that it would remove all of your data since eval evaluates the input string as a command. Using eval on user input assumes that the user is never going to ever write something malformed or malicious, accidentally or otherwise.

Suever
  • 64,497
  • 14
  • 82
  • 101
  • 4
    Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/117732/discussion-on-answer-by-suever-struct-name-from-variable-in-matlab). – Brad Larson Jul 19 '16 at 16:48