How to change the content of file?

Hello,
I I would like to change the content of a .txt file via a for loop, if it is possible.
I would like thw first value to be 10 and the last 250, and I want the content to be changed per 10 (I mean for k=10:10:250).
I am importing the .txt file.
How could I do that?

7 commentaires

Walter Roberson
Walter Roberson le 21 Mai 2020
Is the number the only thing in the file? If so then just keep writing new files ignoring the current content of the file.
Ivan Mich
Ivan Mich le 22 Mai 2020
I would like to do it only with this way. It is important for my code. Yes , the only thing I would like to change is this number
Walter Roberson
Walter Roberson le 22 Mai 2020
in your real file, is the number the only thing that is in the file and it occupies the one and only line in the file? Or are there additional lines? if there are additional lines then is it always the same relative position to change or does the number have to be located after varying amounts of text?
Ivan Mich
Ivan Mich le 22 Mai 2020
Look , I have file with one line. My code needs the line to be changed via a loop. after every iteration I would like to change the number. I am Importing the file that comes from the first iteration.
Would something a simple as:
load Document2.txt -ascii
% do some work
Document2 = Document2 + 10;
% possibly do some more work
save Document2.txt Document2 -ascii
Walter Roberson
Walter Roberson le 22 Mai 2020
save -ascii puts in a line of comments
Bjorn Gustavsson
Bjorn Gustavsson le 22 Mai 2020
@Walter: What version of matlab started with that?

Réponses (1)

Walter Roberson
Walter Roberson le 22 Mai 2020
filename = 'Document2.txt';
while true
Val = load(filename) + 10;
if Val > 250; break; end
fid = fopen(filename, 'wt') ;
fprintf(fid, '%g\n', Val) ;
fclose(fid) ;
end
Not the way that I would implement myself, but for some reason it is important to you to work this way.

Cette question est clôturée.

Question posée :

le 21 Mai 2020

Clôturé :

le 20 Août 2021

Community Treasure Hunt

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

Start Hunting!

Translated by