Hi everybody I tried to import data from notepad file using k=load('a_1.txt') and save again with name b_1.But I need to make this in the loop so, I can load many files have different names like a_1 a_2......a_10. Then I will save them again in the

2 次查看(过去 30 天)
Hi everybody
I tried to import data from notepad file using k=load('a_1.txt') and save again with name b_1.But I need to make this in the loop so, I can load many files have different names like a_1 a_2......a_10. Then I will save them again in the loop with different names like b_1, b_2, b_3 .....b_10. I tried to use the
for x=1:6
load(eval(sprintf('a%d', x));)
z=eval(sprintf('a%d', x));
save eval(sprintf('b%d=z;', x))
end
How can I make this loop to load and save thses files.
Thanks for help
  2 个评论
Stephen23
Stephen23 2017-6-20
编辑:Stephen23 2017-6-20
Using eval is an awful way to solve this task. The documentation explains much better (simpler, neater, faster, more robust, more efficient,...) ways to process a sequence of files:
And also this has been explained many times on this forum:
About the worst solution would be to use eval, you might like to first know what the MATLAB documentation says about it: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
You might also like to read what experienced MATLAB users say about what you are trying to do (hint: they strongly advise against it):
A much better solution is to load your data into one variable, and then simply access the data using indexing and/or fieldnames, e.g. if you use load then always load into an output variable. This will more efficient, neater, more robust, easier to check, easier to debug, faster,...
PS: Microsoft Notepad is a propriety text editor. I suspect you mean to write "text file", because "notepad files" do not exist.
Jan
Jan 2017-6-20
Do I understand correctly: Actually you want to rename the files?
Trust Stephen's suggestion: Avoid eval completely.

请先登录,再进行评论。

回答(2 个)

KSSV
KSSV 2017-6-20
files = dir('*.txt') ;
N = length(files) ;
for i = 1:N
data = load(files(i).name) ;
% new file name
newfile = strcat('b_',num2str(i),'.txt') ;
save(newfile,'data','-ascii')
end

Stephen23
Stephen23 2017-6-20
编辑:Stephen23 2017-6-20
To rename files use movefile.
If you only want to rename the files there is absolutely no point in wasting time reading the data into MATLAB and then saving a new file. movefile is simpler and faster.

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by