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

131 次查看(过去 30 天)
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

采纳的回答

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

更多回答(1 个)

Voss
Voss 2022-5-21
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 个评论
Pablo Fernández
Pablo Fernández 2022-5-21
Thanks for your reply, this works perfectly and it allowed me to understand where was the problem.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by