How to insert a string to a variable name

9 views (last 30 days)
Brook
Brook on 18 Oct 2022
Answered: Walter Roberson on 20 Oct 2022
Hi everyone,
I am trying to insert a string as a variable name, my code is below but file name doesn't read A as 'sub-x421m9_'. At the end I want my file name to be sub-x421m9_
sub_ID={'sub-x421m9_'};
for k=0
A = eval('sub_ID');
[R,P]=corrcoef(sub1);
save(A,'R');
end
  1 Comment
Stephen23
Stephen23 on 18 Oct 2022
Why do you need such an indirect and obfuscated way just to define the filename?
What specifically is stopping you from simply passing the filename itself?

Sign in to comment.

Answers (2)

Steven Lord
Steven Lord on 18 Oct 2022
Should you try to create variables with dynamic names like this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
In addition, sub-x421m9_ is not a valid variable name in MATLAB.
isvarname('sub-x421m9_')
ans = logical
0
Variable names may only contain letters, numbers, and/or the underscore character. The - character is not allowed. When you try to eval that, it is interpreted as trying to subtract the variable (or result of a function call with 0 inputs and 1 output) named x421m9_ from the variable (or result of a function call etc.) named sub.
If all you wanted to do was use that as a file name, that's easy. I'm going to switch to a temporary directory:
cd(tempdir)
mkdir dir1829478
cd dir1829478
There is no file in this directory:
ls
Now make some sample data to save:
sampleDataToSave = 1:10;
and save it.
filename = {'sub-x421m9_'};
save(filename{1}, 'sampleDataToSave')
Note that the file now exists:
ls
sub-x421m9_.mat
and contains the variable sampleDataToSave.
whos('-file', filename{1})
Name Size Bytes Class Attributes sampleDataToSave 1x10 80 double

Walter Roberson
Walter Roberson on 20 Oct 2022
sub_ID={'sub-x421m9_'};
for k=0
A = sub_ID{k+1};
[R,P]=corrcoef(sub1);
save(A,'R');
end

Categories

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