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

1 ビュー (過去 30 日間)
Pablo Fernández
Pablo Fernández 2022 年 5 月 21 日
コメント済み: Pablo Fernández 2022 年 5 月 21 日
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 件のコメント
Pablo Fernández
Pablo Fernández 2022 年 5 月 21 日
It worked as I wanted to, thank you so much.

サインインしてコメントする。

その他の回答 (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.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by