FDS and Matlab: Reading and writing an array in a file text
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
María Plata
le 28 Jan 2020
Réponse apportée : María Plata
le 29 Jan 2020
Good morning.
I have a problem with one script I am creating. The problem comes once I need to rewrite the sentence that is in my text file in order to change the number 330 with another number:
&RAMP ID = 'rampM', T=330, F = 1/
The main problem is that when I rewrite all the sentence the apostrophe tells matlab that the end of the sentences is after the equals and matlab doesn't take all the line from the text file.
I would like to know how to only change the 330 in order to keep the rest of the sentece the same.
Best regards.
Maria.
2 commentaires
Guillaume
le 28 Jan 2020
The answer to your question depends entirely on how you are currently reading and writing the file. We probably need to see some code.
"matlab doesn't take all the line from the text file.". Low level IO functions read whatever you tell them to read, including a whole line if you want, but it's unclear if you're using low-level functions.
Réponse acceptée
Guillaume
le 28 Jan 2020
Oh, your problem is actually with constructing the replacement string, not the actual replacement in the file.
Yes, that's not how you compose text in matlab.
newtext = '&ramp ID = ''ramp M'', T=40, F = 1';
In a char vector, if you want insert actual ' (single quote) characters, you need to double them:
c = 'this a char vector with a '' quote';
You could also work with the newish (R2016) string data type instead of char vectors. In your case, it doesn't make a difference but generally string arrays are easier to work with.
newtext = "&ramp ID = 'ramp M', T=40, F = 1";
In a string, if you want to insert actual " (double quote) characters, you need to double them:
s = "this a string with a "" quote";
Note that your first piece of code can't possibly work. You're closing the file before attempting to read it with textscan. Overall, I'd recommend you use this:
filelines = splitlines(fileread('himoto_1a.txt')); %easiest way to get lines out of a file
filelines{168} = '&ramp ID = ''ramp M'', T=40, F = 1';
%unfortunately, there's no equivalent to fileread for writing file
fid = fopen('himoto_1a.txt','wt');
fprintf(fileID, strjoin(filelines, '\n')); %using strjoin avoids insert a line return at the end of the file
fclose(fid);
0 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Low-Level File I/O dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!