How can I export a string to a .txt file?
136 views (last 30 days)
Show older comments
Hello, I'm working on a project where I need to export some text to a .txt file. Everything I find on the Internet is about exporting data (numbers) but I need to export some text.
I can do this using numbers but I can't do it if it's a string or any kind of text.
function creararchivo
A = 5 ;
save Prueba1.txt A -ascii
end
This code doesn't work as it did when A was 5:
function creararchivo
A = "B" ;
save Prueba1.txt A -ascii
end
Thanks in advance
0 Comments
Accepted Answer
More Answers (1)
Voss
on 21 May 2022
From the documentation for save:
"Use one of the text formats to save MATLAB numeric values to text files. In this case:
- Each variable must be a two-dimensional double array.
[...] If you specify a text format and any variable is a two-dimensional character array, then MATLAB translates characters to their corresponding internal ASCII codes. For example, 'abc' appears in a text file as:
9.7000000e+001 9.8000000e+001 9.9000000e+001"
(That's talking about character arrays, and you showed code where you tried to save a string, but you also said it doesn't work if the variable is any kind of text, which would include character arrays.)
So that explains what's happening because that's essentially the situation you have here.
A = 'B' ;
save Prueba1_char.txt A -ascii
type Prueba1_char.txt % character 'B' written as its ASCII code, 66
A = "B" ;
save Prueba1_string.txt A -ascii
type Prueba1_string.txt % nothing
There are functions you can use to write text to a text file. You might look into fprintf
fid = fopen('Prueba1.txt','w');
fprintf(fid,'%s',A);
fclose(fid);
type Prueba1.txt
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!