How can I declare a char or cell variable using an identifier number?

>> SOLVENT={'S1'}
SOLVENT =
'S1'
>> SOLVENT={'S2'}
SOLVENT =
'S2'
I want to declare the variable SOLVENT , but I need that the last part of the variable (in this case 1 or 2) be given by a variable n. For example
n=1;
>> eval(['SOLVENT={S' num2str(n) '}'])
??? Error using ==> eval
Undefined function or variable 'S1'.
I need to declare this variable as the first line, but using the variable n as the suffix of the name declared. I also tried bit i had the same result.
>> eval(['S={num2str(S' num2str(n) ')}'])
??? Error using ==> eval
Undefined function or variable 'S1'.
I need to create cell variables using a generic string part (in this case S) and as suffix a variable part n.

Answers (3)

It's not clear, to me at least, what you want. Why don't you just declare SOLVENT like this:
SOLVENT = {'S1', 'S2'}
If you want to see cells in it, or use them, you can reference them with an index number enclosed in braces:
fprintf('SOLVENT{1} = %s\nSOLVENT{2} = %s\n',...
SOLVENT{1}, SOLVENT{2});
In the command window:
SOLVENT =
'S1' 'S2'
SOLVENT{1} = S1
SOLVENT{2} = S2
One other possibility is that you want to use dynamic field names, but that's getting into some pretty advanced and tricky stuff - not sure if you really want to do that, as there are simpler ways to accomplish things than resorting to that. You can search for that if you want.

Asked:

on 22 Dec 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!