fprintf break line different arrays
9 次查看(过去 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!