Using fprintf to display values of an array in a particular order?

8 views (last 30 days)
My assignment reads as follows:
Create a table to show the values of sine for angles between 0 and 2 pi.
  • Create a vector of angles values from 0 to 2pi in increments of pi/10
  • Calculate the sine of each of the angles, and group your results in a table that includes the angle and the sine
  • Use disp to create a title for the table and a second disp command to create column headings
  • Use the fprintf function to display the numbers. Display only two values past the decimal point
My attempt at the code is the following:
%%Problem 7.10
% FPRINTF trig tables
angles = 0:pi/10:2*pi;
anglesin = sin(angles);
table1 = [angles', anglesin'];
disp('Sin Table for 0:2pi')
disp('Angle Sin')
fprintf(' %1.2f %1.2f\n',table1(:,1),table1(:,2))
The problem is, no matter how I create the table, it displays the values in the wrong order! For example, instead of showing something like this
Angle | Sine
------------
Angle | Sine
Angle | Sine
Angle | Sine
Angle | Sine
It does this instead:
Angle | Sine
------------
Angle | Angle
Angle | Angle
Sine | Sine
Sine | Sine
It is filling out all the Angles first, then filling out all the Sines. No matter how I setup the source array, it does it incorrectly! Please help, and thanks!

Accepted Answer

Star Strider
Star Strider on 23 Jun 2014
You have to transpose table1 in your print statement:
fprintf(' %1.2f %1.2f\n',table1')
produces:
Sin Table for 0:2pi
Angle Sin
0.00 0.00
0.31 0.31
0.63 0.59
0.94 0.81
1.26 0.95
1.57 1.00
1.88 0.95
2.20 0.81
2.51 0.59
2.83 0.31
3.14 0.00
... etc.
It apparently had to do with how MATLAB assigns variables to the various output fields in the fprintf function.

More Answers (0)

Categories

Find more on Author Block Masks in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!