fprintf using a for loop

9 views (last 30 days)
Ammar
Ammar on 23 Oct 2011
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.

Accepted Answer

Walter Roberson
Walter Roberson on 23 Oct 2011
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 Comments
Ammar
Ammar on 23 Oct 2011
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 on 4 Nov 2011
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))

Sign in to comment.

More Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!