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

조회 수: 133 (최근 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.

댓글을 달려면 로그인하십시오.

카테고리

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