How can I export a string to a .txt file?

136 views (last 30 days)
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

Accepted Answer

dpb
dpb on 21 May 2022
Edited: dpb on 21 May 2022
As documented, save translates character data to ASCII codes with the 'ascii' option. It means it literally!
Use
writematrix(A,'yourfilename.txt')
instead

More Answers (1)

Voss
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
6.6000000e+01
A = "B" ;
save Prueba1_string.txt A -ascii
Warning: Attempt to write an unsupported data type to an ASCII file.
Variable 'A' not written to file.
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
B
  1 Comment
Pablo Fernández
Pablo Fernández on 21 May 2022
Thanks for your reply, this works perfectly and it allowed me to understand where was the problem.

Sign in to comment.

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!