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

1
  • 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. Commented Jul 19, 2016 at 15:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Comments are not for extended discussion; this conversation has been moved to chat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.