How to insert a string to a variable name
9 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Stephen23
2022 年 10 月 18 日
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?
回答 (2 件)
Steven Lord
2022 年 10 月 18 日
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 件のコメント
Walter Roberson
2022 年 10 月 20 日
sub_ID={'sub-x421m9_'};
for k=0
A = sub_ID{k+1};
[R,P]=corrcoef(sub1);
save(A,'R');
end
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!