Home > published > periodTable.m

periodTable

PURPOSE ^

Example of formatted tabular output AND reading and parsing a text file

SYNOPSIS ^

function periodTable

DESCRIPTION ^

Example of formatted tabular output AND reading and parsing a text file
Calculates periods of orbits of planets from a table of radii.
USAGE: >>periodTable

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

function  periodTable
%Example of formatted tabular output AND reading and parsing a text file
%Calculates periods of orbits of planets from a table of radii.
%USAGE: >>periodTable
output='scrn'; fOut=1; 
%output='file';

if output=='file' fOut=fopen('planetPeriods.txt','wt'); end
fprintf('\n\n');

fprintf(fOut,'PLANETARY PROPERTIES TABLE\n');
fprintf(fOut,'========= ========== =====\n\n');

%Define the table formats
formatData='%5s %7.2f %9.2E %6.3f  \n';
formatHeadings='%5s %7s %9s %6s  \n';

fprintf(fOut,formatHeadings,'Name','Radius','Radius', 'Period');
fprintf(fOut,formatHeadings,'    ',' (AU) ',' (km) ', '(year)');
fprintf(fOut,formatHeadings,'----','------','------', '------');

%For more about formated ouput see:
%   http://www.coderwiki.com/wiki/index.php?title=C:Format_string.
%
%Matlab's fprintf borrows all the formatting convenctions from C's printf.
%   See also help http://publications.gbdirect.co.uk/c_book/chapter9/formatted_io.html
%
%Both of these articles contain C-specific information.  Concentrate on
%how they define formatted output with printf and fprintf.
%That is the part that transfers to Matlab.
fIn=fopen('massAndRadius.txt','r');
rEarth=150E6;
secondsPerYear=365.25*3600*24;
   while 1
      line = fgetl(fIn);
      if ~ischar(line), break, end
         [token, remain] = strtok(line); planet=token;  
         if planet(1)=='%', continue, end
         [garbage, remain]=  strtok(remain); [garbage, remain]=  strtok(remain); 
         radiusAU=str2double(strtok(remain)); radiusKm=rEarth*radiusAU;
         period=keplersThird(1000*radiusKm);  periodYears=period/secondsPerYear;
         fprintf(fOut,formatData,planet,radiusAU,radiusKm,periodYears);
   end
fclose(fIn);
if output=='file' fclose(fOut); end
end

function period=keplersThird(R)
%Calculates orbital period (in seconds) for a planet orbiting the sun at a
%distance R (in meters)
%USAGE: keplersThird(150E6)
%>> 3.155E7
G=6.67E-11; mSun=1.99E30;
period=sqrt(4*pi^2*R^3/(G*mSun));
end

Generated on Fri 07-Nov-2008 13:46:59 by m2html © 2005