fprintf break line different arrays
조회 수: 10 (최근 30일)
이전 댓글 표시
[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!
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!