how do i change a variable name from workspace
이전 댓글 표시

i have a sequence of .mat files. When i load the mat files into workspace, the variable names are composed of sing or double underscore such as 'IR0004__, IR 10001_'. Thus, i would like to change these variables to be only number. How can i delete the underscore?
Please suggest Thank you
댓글 수: 4
"Thus, i would like to change these variables to be only number."
Valid variable names must start with a letter, they cannot be "only number".
The easiest solution is to avoid this problem entirely by load-ing into an output variable and accessing its field/s:
S = load(...)
You could then use struct2cell to trivially access the field contents, and place these into one array (numeric, cell, etc) using basic MATLAB indexing. Note that it is actually much easier to process a sequence of .mat files if they contain exactly the same variable names, because then these can be trivially imported into one non-scalar structure, and accessing using simple, efficient indexing.
Tossawon Ngamnet
2018년 7월 25일
As I wrote in my comment, to load the data into one non-scalar array all variables in the .mat files must have exactly the same variables. This appears to not be the case with your .mat files, so you cannot use this method. If the variable names were exactly the same (as they should be) then you can simply do this:
for k = 1:N
S(k) = load(...)
end
As noted, this only works if the variable names are the same! Instead, you could use a cell array:
C = cell(1,N);
for k = 1:N
S = load(...);
C(1) = struct2cell(S);
end
Note that rather than this
['IR',num2str(fidx,'%04d'), '.mat']
you should use sprintf:
sprintf('IR%04d.mat',fidx)
Tossawon Ngamnet
2018년 7월 25일
편집: Tossawon Ngamnet
2018년 7월 25일
채택된 답변
추가 답변 (1개)
Giridharan Kumaravelu
2018년 7월 24일
편집: Giridharan Kumaravelu
2018년 7월 24일
getname = @(x) inputname(1);
IR0004__ = 10;
str = getname(IR0004__);
newstr = erase(str,'_');
eval([newstr '=' str ';']);
clear(str);
This could help you rename one variable. But if you are looking to rename the variables containing only numbers in the name, that will not be valid variable name in any programming language.
Hope this helps!
댓글 수: 4
Tossawon Ngamnet
2018년 7월 24일
편집: Tossawon Ngamnet
2018년 7월 24일
Giridharan Kumaravelu
2018년 7월 24일
1. How are you uploading the matfiles to the workspace? Using any command line or anything else? 2. How are you converting the matfiles to TIF files?
Tossawon Ngamnet
2018년 7월 24일
편집: Stephen23
2018년 7월 24일
"Sorting is not consecutive."
You can easily sort the filenames by downloading my FEX submission natsortfiles:
"Thus, i cannot use for loop to initial the variable names correctly."
Accessing variable names in a loop is not recommended:
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!