How to insert a string to a variable name

조회 수: 9 (최근 30일)
Brook
Brook 2022년 10월 18일
답변: Walter Roberson 2022년 10월 20일
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
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
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_')
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 2022년 10월 20일
sub_ID={'sub-x421m9_'};
for k=0
A = sub_ID{k+1};
[R,P]=corrcoef(sub1);
save(A,'R');
end

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by