필터 지우기
필터 지우기

fprintf break line different arrays

조회 수: 5 (최근 30일)
AM
AM 2018년 11월 8일
편집: Stephen23 2018년 11월 8일
[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!

채택된 답변

Stephen23
Stephen23 2018년 11월 8일
편집: Stephen23 2018년 11월 8일
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
madhan ravi
madhan ravi 2018년 11월 8일
why use loop ?
Stephen23
Stephen23 2018년 11월 8일
편집: Stephen23 2018년 11월 8일
"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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by