fprintf break line different arrays

10 visualizaciones (últimos 30 días)
AM
AM el 8 de Nov. de 2018
Editada: Stephen23 el 8 de Nov. de 2018
[Edited] I use 2 arrays here as examples but I actually have several
I have the following arrays:
a=[1 2 3 4 5 6 7 8 9 10 11];
b=[12 13 14 15 16];
And I want to write a text file that gives me:
1 2 3 4 5 6 7 8 9 10
11
12 13 14 15 16
This is my code:
fmti = repmat(' % 12d',1,10);
fmti = [fmti(2:end),'\n'];
fprintf(file,fmti,a);
fprintf(file,fmti,b);
However this gives me a file where 1 through 10 are written on the same line and 11 through 16 are on the same line.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16
I know it's because I set the number of elements to 10 (and that is because the maximum number of elements per line will always be 10) but I would like fprintf to do a break line when it prints different vectors.
I need a code that will always write 10 elements per line maximum but will write different vectors in different lines.
Any help is appreciated, thank you!

Respuesta aceptada

Stephen23
Stephen23 el 8 de Nov. de 2018
Editada: Stephen23 el 8 de Nov. de 2018
It is easier when you put your vectors into one cell array:
C = {[1,2,3,4,5,6,7,8,9,10,11],[12,13,14,15,16]};
F = [repmat('% 4d',1,10),'\n'];
for k = 1:numel(C)
fprintf(F,C{k})
if mod(numel(C{k}),10)
fprintf('\n')
end
end
prints this:
1 2 3 4 5 6 7 8 9 10
11
12 13 14 15 16
  2 comentarios
madhan ravi
madhan ravi el 8 de Nov. de 2018
why use loop ?
Stephen23
Stephen23 el 8 de Nov. de 2018
Editada: Stephen23 el 8 de Nov. de 2018
"why use loop ?"
To avoid writing duplicate code, to allow for an arbitrary number of vectors, to allow the newline to be added after each vector, and to allow for the if statement. I presumed that AM would not want two newlines to be adjacent (i.e. a blank line), and if is a trivial way to achieve that.
Of course a loop is not the only way to achieve that, but it is clear and efficient.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by