MATLAB Answers

for loop with eval and sprintf with underscore in

조회 수: 24(최근 30일)
Elisa
Elisa 2014년 4월 7일
댓글: Elisa 2014년 4월 8일
Sorry about that,
I've been trying really hard to find any solution from other answers, but or I don't understand them or it doesn't work.
I've also red that is bad to dynamically use 'eval' and 'sprintf', however, even though I'm willing to learn, I am not able to do in another way (and I've tried it).
I've many .txt file:
X12345678_1_ABC_ABCD_ABCDE_ABCDEF.txt
% Load .txt files into workspace
files = dir('*.txt');
for i=1:length(files);
eval(['load ' files(i).name ' -ascii']);
end
%% I dynamically try to do something with my variable
for i=1:length(files);
filename = files(i).name(1:end-4); %%%I get out the .txt
temp = eval(sprintf('X%s\_1\_ABC\_ABCD\_ABCDE\_ABCDEF',filename));
%insert the matrix of the text file into a new 3D matrix
threeD_matrix (i,:,f) = temp;
end
Warning: Escape sequence '_' is not valid. See 'help sprintf' for valid escape sequences. Error using eval Undefined function or variable
Thank you so much for your help!!!!!

답변(3개)

Jan
Jan 2014년 4월 7일
Two general advices:
1. Avoid eval in general:
eval(['load ' files(i).name ' -ascii']);
Better:
load(files(i).name, '-ascii');
2. Join folder names by fullfile instead of sprintf with hard coded separators.
  댓글 수: 1
Elisa
Elisa 2014년 4월 8일
Thanks Jan! I didn't know, who to do it! I'll follow your tips for next time! Thanks a lot!

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2014년 4월 7일
편집: Star Strider 2014년 4월 7일
To put a backslash (\) into a string, you need to use a double backslash (\\):
filename = 'myfile.txt';
R = sprintf('X%s\\_1\\_ABC\\_ABCD\\_ABCDE\\_ABCDEF', filename)
produces:
R =
Xmyfile.txt\_1\_ABC\_ABCD\_ABCDE\_ABCDEF
The ‘eval’ function is not considered efficient programming practice, but it may be the only way to get a variable generated as a string into the workspace as a variable. It is not really ‘wrong’ though.
  댓글 수: 7
Star Strider
Star Strider 2014년 4월 7일
My pleasure!
Sorry for the delay — sleeping here (GMT-6).

댓글을 달려면 로그인하십시오.


Elisa
Elisa 2014년 4월 7일
Dear Star Stride,
Thanks a lot again!
I used
disp(....) and the variable is there
which X12345678_1_ABC_ABCD_ABCDE_ABCDEF -all
says that:
X12345678_1_ABC_ABCD_ABCDE_ABCDEF is a variable
which X12345678_1_ABC_ABCD_ABCDE_ABCDEF.txt -all
says that:
X12345678_1_ABC_ABCD_ABCDE_ABCDEF.txt not found
datfile = which('X12345678_1_ABC_ABCD_ABCDE_ABCDEF.txt','-all')
gives: datfile = {}
  댓글 수: 2
Star Strider
Star Strider 2014년 4월 7일
My pleasure!
Sorry for the delay — sleeping here (GMT-6).

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by