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

1 Ansicht (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 20 Jun. 2017
Bearbeitet: Stephen23 am 20 Jun. 2017
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 am 20 Jun. 2017
Do I understand correctly: Actually you want to rename the files?
Trust Stephen's suggestion: Avoid eval completely.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

KSSV
KSSV am 20 Jun. 2017
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 am 20 Jun. 2017
Bearbeitet: Stephen23 am 20 Jun. 2017
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.

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by