Borrar filtros
Borrar filtros

How correctly use fprintf

1 visualización (últimos 30 días)
Maria
Maria el 12 de Ag. de 2015
Editada: Stephen23 el 12 de Ag. de 2015
Hi,
could someone explain me how to correctly use fprint?
I made this test
testA =[1;2;3];
testB =[4;5;6];
fid = fopen('test_t.txt','w');
for i = 1 :3
fprintf(fid,'%d %d \n',testA(i),testB(i));
end
fclose(fid);
I was hoping to find this result in the .txt file
1 4
2 5
3 6
In the .txt file I see this " 1 4 2 5 3 6". But is funny because now that I tried to copy and paste the content of the text file in this question, I got this
1 4
2 5
3 6
Can someone explain me:
  1. what does it mean " %d" in fprintf and where I find the documentation about it?
  2. Why I see something in the .txt file that does not look like what I want, except when I do copy and paste....
Thanks
  1 comentario
Maria
Maria el 12 de Ag. de 2015
Btw, if I take the number in the text file, copy and paste on excel, and from there save it in a text file, then I see them in the way I want to see them. Any idea? I would like to skip a text - excel -text path, and directly see the data in the text file as I expect them.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 12 de Ag. de 2015
Editada: Stephen23 el 12 de Ag. de 2015
Textfile Newlines
Try adding 't' to the fopen permissions string:
fid = fopen('test_t.txt','wt');
It is because the Windows newline actually consists of two characters, and simply using '\n' is not enough for some windows programs. The easiest solution is to add the 't' option to fopen, which makes this change automatically (for both reading and writing files). You might like to do this for all text files. You can read more about this in the fopen documentation.
fprintf Format String
%d is explained in the fprintf documentation as printing an "Integer, signed", which means it prints the numeric value provided as base-10 numeric digits in the file.
The MATLAB documentation is actually quite easy to read and navigate, you should try practice browsing it and try some of the examples that it includes!
Bonus Simplified Code
Note that you can simplify your code by removing the loop, because fprintf also works with arrays (but remember that MATLAB is column-major!):
>> testA =[1;2;3];
>> testB =[4;5;6];
>> fid = fopen('test.txt','wt');
>> fprintf(fid,'%d %d\n',[testA,testB].')
>> fclose(fid)
  1 comentario
Maria
Maria el 12 de Ag. de 2015
Editada: Maria el 12 de Ag. de 2015
Thank you! That solved my problem! Thank you also for the link about the documentation, I don't know what I have looked for, but I had not found it :D

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Migrate GUIDE Apps en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by