How to insert a string to a variable name
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 18 de Oct. de 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?
Respuestas (2)
Steven Lord
el 18 de Oct. de 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_')
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
and contains the variable sampleDataToSave.
whos('-file', filename{1})
0 comentarios
Walter Roberson
el 20 de Oct. de 2022
sub_ID={'sub-x421m9_'};
for k=0
A = sub_ID{k+1};
[R,P]=corrcoef(sub1);
save(A,'R');
end
0 comentarios
Ver también
Categorías
Más información sobre Variables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!