fprintf using a for loop

조회 수: 11 (최근 30일)
Ammar
Ammar 2011년 10월 23일
Hello,
I seem to be having trouble figuring out how to make a table using fprintf using a for loop.
I currently have one cell array and 3 row vectors defined as such:
C = {’a’, ’bb’, ’ccc’, ’dddd’, ’eeeee’};
x = [6.715, -12.075, 7.172, 16.302, 4.889];
y = [-134.98869, 303.49235, 72.54042, -6.30549, 71.47429];
z = [14380, 0.00325, -7549, 13700, -0.00017];
My task is to create a table using fprintf that looks exactly like the following:
x C y C z
---------------------------------------------------
6.715 a -134.98869 a +1.438E+004
-12.075 bb 303.49235 bb +3.250E-003
7.172 ccc 72.54042 ccc -7.549E+003
16.302 dddd -6.30549 dddd +1.370E+004
4.889 eeeee 71.47429 eeeee -1.700E-004
Any help would be appreciated. Thanks.

채택된 답변

Walter Roberson
Walter Roberson 2011년 10월 23일
Well, after the header lines, when you get to line #K, you would be wanting to emit
x(K), C{K}, y(K), C{K}, z(K)
Everything beyond that is no longer a difficulty with using fprintf() in "for" loop, and is instead a difficulty in using fprintf() to emit numbers in particular formats, occupying particular number of columns, and having particular alignments.
I will give you a hint: experiment with %5s and %-5s formats when you are printing out C{K}.
  댓글 수: 2
Ammar
Ammar 2011년 10월 23일
Thank you for the input. The %5s and %-5s hints really helped. There is just one more thing that I do not understand. In the for loop, what steps should I take? For instance, should I do:
for i=1:5
x=x(i)
y=y(i)
C=C{i}
z=z(i)
fprintf('%7.3f %5s %9.5f %-5s %5.3e',x(i), C{i}, y(i), C{i}, z(i))
Aside from this, I have tried everything I can think of. I guess its important to know it has only been one month since I started learning MATLAB, so there is a lot I do not know.
Once again, thanks for everything.
Walter Roberson
Walter Roberson 2011년 11월 4일
Remove the statements
x=x(i)
y=y(i)
C=C{i}
z=z(i)
as they are going to wipe out the variables you are trying to print out!
The only change I would make to
fprintf('%7.3f %5s %9.5f %-5s %5.3e',x(i), C{i}, y(i), C{i}, z(i))
is
fprintf('%7.3f %5s %9.5f %-5s %5.3e\n',x(i), C{i}, y(i), C{i}, z(i))

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by