Difference between revisions of "Matlab IO"
(→Terminal and File Output in MATLAB) |
|||
Line 1: | Line 1: | ||
− | == | + | == Output in MATLAB == |
− | + | ||
+ | Output in Matlab can be accomplished in several ways. Here we briefly | ||
+ | summarize the various output options, which are discussed in more | ||
+ | detail below. | ||
+ | |||
+ | * [[#Basic_output_using_DISP|'''<tt>disp</tt>''']] - The <tt>disp</tt> command is the simplest way to dump information to the command window, but does not allow control over formatting, and cannot be used for file output. | ||
− | * | + | * [[#Formatted_output_using_FPRINTF|'''<tt>fprintf</tt>''']] - The <tt>fprintf</tt> command allows much more control over output, and can be used to dump results to the command window or to files. |
− | * | + | * [[#Saving_Variables_with_SAVE|'''<tt>save</tt>''']] - The <tt>save</tt> command can be used to save variables to disk. The [[#load|'''<tt>load</tt>''']] command can then be used to load them back from disk. |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | === | + | === Basic output using DISP === |
− | |||
+ | The '''<tt>disp</tt>''' command is the simplest output command. It can | ||
+ | be used to output variable contents or text strings: | ||
+ | <source lang="matlab"> | ||
+ | T = linspace(50,250,5); | ||
+ | disp('the temperatures (C) are:'); | ||
+ | disp( T ); | ||
+ | </source> | ||
− | |||
− | + | === Formatted output using FPRINTF === | |
− | |||
− | |||
− | |||
− | The <tt> | + | The '''<tt>fprintf</tt>''' command provides significantly more control |
− | + | over output. The basic usage of this command is: | |
− | + | <source lang="matlab"> | |
− | + | fprintf( 'formatting & text', v1, v2, ... vn ); % print to command window | |
− | + | fprintf( fid, 'formatting & text', v1, v2, ... vn ); % print to a file | |
</source> | </source> | ||
− | + | This prints several variables, interspersed with text, to a file with | |
− | + | the identifier <tt>fid</tT>. If no file id is specified, the output | |
− | + | goes to the screen. The [[#Formatting_Output|formatting]] is controlled by the | |
− | + | formatting string. | |
− | + | ||
− | + | ==== Controlling Formatting ==== | |
− | + | ||
− | + | Output is formatted using a string in the form <tt>'''%a.bc'''</tt>, where: | |
− | + | * '''<tt>a</tt>''' represents the ''minimum'' width to use for the output. Note that if you don't want a minimum set, you can always use 0 here. | |
− | + | * '''<tt>b</tt>''' indicates how many digits past the decimal point to use. | |
− | + | * '''<tt>c</tt>''' indicates the formatting scheme. While there are many schemes, the most common are: | |
− | + | ** '''<tt>f</tt>''' - floating point format such as 123.45. | |
− | + | ** '''<tt>e</tt>''' - scientific notation format such as 1.2345e2. | |
− | + | ** '''<tt>s</tt>''' - string format (used to print out text). | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | * <tt> | ||
− | |||
− | |||
− | |||
+ | Occassionally we simplify this to <tt>'''%ac'''</tt> or <tt>'''%c'''</tt>, both of which are also valid. | ||
− | + | Here are some examples: | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
{| border="1" cellpadding="5" cellspacing="0" | {| border="1" cellpadding="5" cellspacing="0" | ||
− | + | |- style="background:lightgrey" | |
− | |- | + | ! Matlab Code !! Output |
− | ! | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
|- | |- | ||
|<source lang="matlab"> | |<source lang="matlab"> | ||
− | + | theta = pi/3; % define the angle. | |
− | |||
− | |||
+ | % Print the cos of the angle to the command window. | ||
+ | % Format using a floating point number with | ||
+ | % 3 decimal places. | ||
+ | fprintf('cos(%0.3f) = %0.3f\n', theta, cos(theta)); | ||
− | + | % print out the same information in a different form. | |
− | + | % Here we use scientific notation with three | |
− | + | % significant figures. | |
− | + | fprintf('The cos of %0.2e is %0.2e\n',theta,cos(theta)); | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | + | fprintf('cos(%f) = %f\n',theta,cos(theta)); | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
</source> | </source> | ||
− | | | + | |<pre> |
+ | cos(1.047) = 0.500 | ||
+ | The cos of 1.05e+00 is 5.00e-01 | ||
+ | cos(1.047198) = 0.500000 | ||
+ | </pre> | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | % print a table of angles and cos, sin of those angles. | ||
+ | % Each column in the table is 12 spaces wide. | ||
+ | npts = 10; | ||
+ | theta = linspace(0,180,npts) * pi/180; | ||
+ | % print the column headers. | ||
+ | fprintf('%12s %12s %12s %12s\n\n','theta (rad)',... | ||
+ | 'theta (deg)','cos(theta)','sin(theta)'); | ||
− | + | % print the data with three decimal places, and use | |
− | + | % fields that are 12 spaces wide. Put a new line | |
− | + | % after each row. | |
− | + | for i=1:npts | |
− | + | fprintf('%12.3f %12.3f %12.3f %12.3f\n',theta(i),... | |
− | + | theta(i)/pi*180,cos(theta(i)),sin(theta(i))); | |
− | + | end | |
− | |||
</source> | </source> | ||
+ | |<pre> theta (rad) theta (deg) cos(theta) sin(theta) | ||
+ | 0.000 0.000 1.000 0.000 | ||
+ | 0.349 20.000 0.940 0.342 | ||
+ | 0.698 40.000 0.766 0.643 | ||
+ | 1.047 60.000 0.500 0.866 | ||
+ | 1.396 80.000 0.174 0.985 | ||
+ | 1.745 100.000 -0.174 0.985 | ||
+ | 2.094 120.000 -0.500 0.866 | ||
+ | 2.443 140.000 -0.766 0.643 | ||
+ | 2.793 160.000 -0.940 0.342 | ||
+ | 3.142 180.000 -1.000 0.000</pre> | ||
− | === | + | |- |
+ | |<source lang="matlab"> | ||
+ | year = [ 1750 1800 1850 1900 1950 2005 ]; | ||
+ | pop = [ 791000 978000 1262000 165000 2518629 6453628 ]; | ||
+ | for i=1:length(year) | ||
+ | fprintf('The world population in %1.0f was %1.2e\n',year(i),pop(i) ); | ||
+ | end | ||
+ | </source> | ||
+ | Data used in this example is from [http://en.wikipedia.org/wiki/World_population] | ||
+ | |<pre> | ||
+ | The world population in 1750 was 7.91e+05 | ||
+ | The world population in 1800 was 9.78e+05 | ||
+ | The world population in 1850 was 1.26e+06 | ||
+ | The world population in 1900 was 1.65e+05 | ||
+ | The world population in 1950 was 2.52e+06 | ||
+ | The world population in 2005 was 6.45e+06 | ||
+ | </pre> | ||
− | + | |- | |
− | <source lang="matlab"> | + | |<source lang="matlab"> |
− | + | names = {'Bob','Jill','Carl','Steve'}; | |
+ | for i=1:length(names) | ||
+ | fprintf('%s\n',names{i}); | ||
+ | end | ||
</source> | </source> | ||
− | + | |<pre> | |
− | + | Bob | |
+ | Jill | ||
+ | Carl | ||
+ | Steve | ||
+ | </pre> | ||
+ | |} | ||
− | + | In the above examples, you may have noticed that we used <tt>\n</tt>. | |
+ | This is a ''control character'' that produces a carriage return (new | ||
+ | line). There are many control characters, summarized in the following | ||
+ | table: | ||
− | {| border="1" cellpadding=" | + | {| border="1" cellpadding="2" cellspacing="0" |
|+ '''Control Characters for Output Formatting''' | |+ '''Control Characters for Output Formatting''' | ||
|- style="background:lightgrey" | |- style="background:lightgrey" | ||
− | ! Control Code !! Description !! Example | + | ! Control Code !! Description !! Matlab Example !! Output |
|- | |- | ||
| <tt>\n</tt> || New Line | | <tt>\n</tt> || New Line | ||
Line 163: | Line 157: | ||
fprintf('Hello,\nWorld\n'); | fprintf('Hello,\nWorld\n'); | ||
</source> | </source> | ||
+ | |<pre> | ||
+ | Hello, | ||
+ | World | ||
+ | </pre> | ||
|- | |- | ||
| <tt>\t</tt> || A Tab character (useful for spacing) | | <tt>\t</tt> || A Tab character (useful for spacing) | ||
|<source lang="matlab"> | |<source lang="matlab"> | ||
− | fprintf('\tline 1 \ | + | fprintf('\tline 1\nline 2\n'); |
</source> | </source> | ||
+ | |<pre> | ||
+ | line 1 | ||
+ | line 2 | ||
+ | </pre> | ||
|- | |- | ||
| <tt>\\</tt> || Inserts a backslash | | <tt>\\</tt> || Inserts a backslash | ||
|<source lang="matlab"> | |<source lang="matlab"> | ||
− | fprintf(' | + | fprintf('backslash: \\'); |
− | fprintf(' | + | fprintf(' backslash: \\\nthen a new line\n'); |
</source> | </source> | ||
+ | |<pre> | ||
+ | backslash: \ A backslash: \ | ||
+ | and then a new line | ||
+ | </pre> | ||
|- | |- | ||
− | | <tt> | + | |<tt>′′</tt> || Inserts a single quote |
|<source lang="matlab"> | |<source lang="matlab"> | ||
a = pi; | a = pi; | ||
fprintf('The value of ''a'' is %1.3f\n',a); | fprintf('The value of ''a'' is %1.3f\n',a); | ||
</source> | </source> | ||
+ | |<pre> | ||
+ | The value of 'a' is 3.142 | ||
+ | </pre> | ||
|- | |- | ||
| <tt>%%</tt> || Inserts a % sign | | <tt>%%</tt> || Inserts a % sign | ||
Line 186: | Line 195: | ||
fprintf('Your score is %2.0f%%\n',100*score); | fprintf('Your score is %2.0f%%\n',100*score); | ||
</source> | </source> | ||
− | + | |<pre> | |
− | + | Your score is 75% | |
− | + | </pre> | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |< | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | </ | ||
|} | |} | ||
Line 260: | Line 244: | ||
=== File Output === | === File Output === | ||
− | The <tt>fprintf</tt> command may be used to write formatted output to files. | + | |
+ | The <tt>fprintf</tt> command may be used to write formatted output to | ||
+ | files. This requires three steps: | ||
# Open the file for writing. Use the '''<tt>fopen</tt>''' command to open files. | # Open the file for writing. Use the '''<tt>fopen</tt>''' command to open files. | ||
− | # Write to the file using the [[# | + | # Write to the file using the [[#Formatted_output_using_FPRINTF|'''<tt>fprintf</tt>''' command]]. |
# Close the file using the '''<tt>fclose</tt>''' command. | # Close the file using the '''<tt>fclose</tt>''' command. | ||
Line 305: | Line 291: | ||
− | === Saving Variables with SAVE === | + | === Saving Variables with SAVE === |
− | {{ | + | |
+ | The <tt>save</tt> command may be used to save any variables defined in | ||
+ | Matlab to a file. You can then <tt>load</tt> this file back into | ||
+ | Matlab and your variables will be defined. The basic syntax is: | ||
+ | |||
+ | <source lang="matlab"> | ||
+ | save FILENAME; % save ALL variables to a file called "FILENAME.mat" | ||
+ | save FILENAME x1 x2 y; % save only x1 x2 and y to "FILENAME.mat" | ||
+ | </source> | ||
+ | |||
+ | <span id="load"></span>. | ||
+ | To load the file, use | ||
+ | <source lang="matlab"> | ||
+ | load FILENAME; | ||
+ | </source> | ||
+ | |||
+ | For example: | ||
+ | {| border="1" cellpadding="10" cellspacing="0" | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | clear; | ||
+ | a = rand(3); | ||
+ | b = 1:5:100; | ||
+ | c = {'Bob','Fred','Kerry','Jill'}; | ||
+ | save myVars; % save all variables to the file "myVars.dat" | ||
+ | |||
+ | clear; % now no variables are defined. | ||
+ | load myVars; % loads the file myVariables.mat | ||
+ | who; % a, b, and c are defined again. | ||
+ | |||
+ | save myVars b c; % save only b and c. | ||
+ | clear; % now no variables are defined. | ||
+ | load myVars; | ||
+ | who; % b and c are defined. a is not. | ||
+ | </source> | ||
+ | |} | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | == Input in MATLAB == | ||
+ | Input can be accomplished in several ways in Matlab: | ||
+ | |||
+ | * Interactive input from the user. This is accomplished using the [[#The_INPUT_command|<tt>input</tt>]] command. | ||
+ | |||
+ | * Reading files from disk. There are two common methods to do this: using [[#The_FSCANF_command|<tt>fscanf</tt>]] command and using the [[#load|'''<tt>load</tt>''']] command. | ||
+ | |||
+ | |||
+ | === The INPUT command === | ||
+ | The basic syntax for the <tt>input</tt> command is: | ||
+ | {| border="0" cellpadding="10" cellspacing="0" | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | x = input('text to command window'); | ||
+ | </source> | ||
+ | |} | ||
+ | This outputs the given text to the command window. The user can then enter a value and it will be stored in <tt>x</tt>. | ||
+ | |||
+ | |||
+ | === The FSCANF command === | ||
+ | |||
+ | There are three steps to read from a file: | ||
+ | # Open the file using <tt>'''fopen'''</tt> | ||
+ | # Read from the file using <tt>'''fscanf'''</tt> | ||
+ | # Close the file using <tt>'''fclose'''</tt> | ||
+ | |||
+ | The <tt>fscanf</tt> command is used primarily for reading from files. The basic syntax is: | ||
+ | {| cellpadding="10" style="background-color:cornsilk" | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | value = fscanf( fid, format, size ); | ||
+ | </source> | ||
+ | |- | ||
+ | | | ||
+ | {| border="1" cellpadding="5" cellspacing="0" style="background-color:cornsilk" | ||
+ | |- valign="top" | ||
+ | | '''fid''' || The identifier for the file to read from. This is obtained using the [[#Opening_and_Closing_Files|<tt>fopen</tt>]] command. | ||
+ | |- valign="top" | ||
+ | | '''format''' || A text string indicating the format to use when reading values from the file. This is of the form <tt>%Na</tt>, where <tt>N</tt> specifies the width to read and <tt>f</tt> specifies the format to read. | ||
+ | {| cellpadding="5" style="background-color:Cornsilk" | ||
+ | |- | ||
+ | | '''<tt>%c</tt>''' || Reads a character (e.g. "q") | ||
+ | |- | ||
+ | | '''<tt>%s</tt>''' || Reads a character string (e.g. "quiet") | ||
+ | |- | ||
+ | | '''<tt>%d</tt>''' || Reads an integer (e.g. 12345) | ||
+ | |- | ||
+ | | '''<tt>%f</tt>''' || Reads a floating point number (e.g. 5.62) | ||
+ | |} | ||
+ | |- valign="top" | ||
+ | | '''size''' || OPTIONAL - sets a maximum limit on the number of entries to be read from the file. If omitted, then all of the file may be read. Valid specifications are: | ||
+ | * <tt>N</tt> - read at most <tt>N</tt> entries from the file. | ||
+ | * <tt>inf</tt> - read at most to the end of the file. | ||
+ | * <tt>[M,N]</tt> - read <tt>M*N</tt> entries from the file and arrange them into an <tt>M x N</tt> matrix. | ||
+ | |} | ||
+ | |} | ||
+ | |||
+ | |||
+ | ==== Opening and Closing Files ==== | ||
− | == | + | Before reading from a file, we must open it. This is done using the <tt>fopen</tt> command: |
− | {{ | + | {| cellpadding="10" |
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | fid = fopen('filename','r'); % opens a file named "filename" for reading. | ||
+ | </source> | ||
+ | |} | ||
+ | This assigns an identifier to <tt>fid</tt> that can be used in subsequent file operations (reading, closing, etc.). The <tt>'r'</tt> indicates that this file is to be read from. Options are: | ||
+ | {| border="1" cellpadding="5" cellspacing="0" | ||
+ | |+ '''Flags for <tt>fopen</tt>''' | ||
+ | |- | ||
+ | ! Flag !! Description | ||
+ | |- | ||
+ | | '''<tt>'r'</tt>''' || Open a file for reading. | ||
+ | |- | ||
+ | | '''<tt>'w'</tt>''' || Open a file for writing (creates the file if it doesn't already exist). An existing file will be overwritten. | ||
+ | |- | ||
+ | | '''<tt>'a'</tt>''' || Open a file and append it (creates the file if it doesn't already exist). | ||
+ | |} | ||
+ | |||
+ | After you are done with a file, you should close it using the <tt>fclose</tt> command: | ||
+ | {| cellpadding="10" | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | fclose(fid); % closes the file referred to be "fid" | ||
+ | </source> | ||
+ | |} | ||
+ | |||
+ | |||
+ | ==== A Simple Example ==== | ||
+ | {| border="1" cellpadding="5" cellspacing="0" | ||
+ | |- | ||
+ | ! File "ages.dat" !! Matlab Commands !! Explanation | ||
+ | |- valign="top" | ||
+ | | <pre>Fred 64 | ||
+ | Bob 32 | ||
+ | Julia 49</pre> | ||
+ | |<source lang="matlab"> | ||
+ | file = fopen('ages.dat','r'); | ||
+ | name = fscanf( file, '%s', 1 ); | ||
+ | age = fscanf( file, '%s' ); | ||
+ | fclose(file); | ||
+ | </source> | ||
+ | | Reads a string number into the variable <tt>name</tt>. Note the "1" at the end of this statement. If we didn't use "1" when reading the name, then it would have read the entire file into the string. After reading the name, we read the age into the variable <tt>age</tt>. | ||
+ | |} | ||
+ | |||
+ | If we wanted to read the whole file, we would need a few additional things: | ||
+ | * A [[Matlab_Arrays#Cell_Arrays|cell array]] to hold the names | ||
+ | * An [[Matlab_Arrays|array]] to hold the ages. | ||
+ | * A way to determine when we hit the end of the file. This is done using the <tt>'''feof'''(fid)</tt> command. | ||
+ | Using these concepts, we can now read the file. | ||
+ | {| cellpadding="10" | ||
+ | |- | ||
+ | |<source lang="matlab"> | ||
+ | fid = fopen('ages.dat','r'); % opens the file "ages.dat" for reading. | ||
+ | i = 1; | ||
+ | names = {}; | ||
+ | ages = []; | ||
+ | while ~feof(fid) | ||
+ | names{i} = fscanf(fid,'%s',1); % read the name. | ||
+ | age(i) = fscanf(fid,'%i'); % read the age. | ||
+ | i = i+1; % get ready to read the next line | ||
+ | end | ||
+ | fclose(fid); % close the file. | ||
+ | </source> | ||
+ | |} |
Revision as of 09:33, 3 October 2008
Contents
Output in MATLAB
Output in Matlab can be accomplished in several ways. Here we briefly summarize the various output options, which are discussed in more detail below.
- disp - The disp command is the simplest way to dump information to the command window, but does not allow control over formatting, and cannot be used for file output.
- fprintf - The fprintf command allows much more control over output, and can be used to dump results to the command window or to files.
- save - The save command can be used to save variables to disk. The load command can then be used to load them back from disk.
Basic output using DISP
The disp command is the simplest output command. It can be used to output variable contents or text strings:
T = linspace(50,250,5);
disp('the temperatures (C) are:');
disp( T );
Formatted output using FPRINTF
The fprintf command provides significantly more control over output. The basic usage of this command is:
fprintf( 'formatting & text', v1, v2, ... vn ); % print to command window
fprintf( fid, 'formatting & text', v1, v2, ... vn ); % print to a file
This prints several variables, interspersed with text, to a file with the identifier fid. If no file id is specified, the output goes to the screen. The formatting is controlled by the formatting string.
Controlling Formatting
Output is formatted using a string in the form %a.bc, where:
- a represents the minimum width to use for the output. Note that if you don't want a minimum set, you can always use 0 here.
- b indicates how many digits past the decimal point to use.
- c indicates the formatting scheme. While there are many schemes, the most common are:
- f - floating point format such as 123.45.
- e - scientific notation format such as 1.2345e2.
- s - string format (used to print out text).
Occassionally we simplify this to %ac or %c, both of which are also valid.
Here are some examples:
Matlab Code | Output |
---|---|
theta = pi/3; % define the angle.
% Print the cos of the angle to the command window.
% Format using a floating point number with
% 3 decimal places.
fprintf('cos(%0.3f) = %0.3f\n', theta, cos(theta));
% print out the same information in a different form.
% Here we use scientific notation with three
% significant figures.
fprintf('The cos of %0.2e is %0.2e\n',theta,cos(theta));
fprintf('cos(%f) = %f\n',theta,cos(theta));
|
cos(1.047) = 0.500 The cos of 1.05e+00 is 5.00e-01 cos(1.047198) = 0.500000 |
% print a table of angles and cos, sin of those angles.
% Each column in the table is 12 spaces wide.
npts = 10;
theta = linspace(0,180,npts) * pi/180;
% print the column headers.
fprintf('%12s %12s %12s %12s\n\n','theta (rad)',...
'theta (deg)','cos(theta)','sin(theta)');
% print the data with three decimal places, and use
% fields that are 12 spaces wide. Put a new line
% after each row.
for i=1:npts
fprintf('%12.3f %12.3f %12.3f %12.3f\n',theta(i),...
theta(i)/pi*180,cos(theta(i)),sin(theta(i)));
end
|
theta (rad) theta (deg) cos(theta) sin(theta) 0.000 0.000 1.000 0.000 0.349 20.000 0.940 0.342 0.698 40.000 0.766 0.643 1.047 60.000 0.500 0.866 1.396 80.000 0.174 0.985 1.745 100.000 -0.174 0.985 2.094 120.000 -0.500 0.866 2.443 140.000 -0.766 0.643 2.793 160.000 -0.940 0.342 3.142 180.000 -1.000 0.000 |
year = [ 1750 1800 1850 1900 1950 2005 ];
pop = [ 791000 978000 1262000 165000 2518629 6453628 ];
for i=1:length(year)
fprintf('The world population in %1.0f was %1.2e\n',year(i),pop(i) );
end
Data used in this example is from [1] |
The world population in 1750 was 7.91e+05 The world population in 1800 was 9.78e+05 The world population in 1850 was 1.26e+06 The world population in 1900 was 1.65e+05 The world population in 1950 was 2.52e+06 The world population in 2005 was 6.45e+06 |
names = {'Bob','Jill','Carl','Steve'};
for i=1:length(names)
fprintf('%s\n',names{i});
end
|
Bob Jill Carl Steve |
In the above examples, you may have noticed that we used \n. This is a control character that produces a carriage return (new line). There are many control characters, summarized in the following table:
Control Code | Description | Matlab Example | Output |
---|---|---|---|
\n | New Line | fprintf('Hello,\nWorld\n');
|
Hello, World |
\t | A Tab character (useful for spacing) | fprintf('\tline 1\nline 2\n');
|
line 1 line 2 |
\\ | Inserts a backslash | fprintf('backslash: \\');
fprintf(' backslash: \\\nthen a new line\n');
|
backslash: \ A backslash: \ and then a new line |
′′ | Inserts a single quote | a = pi;
fprintf('The value of ''a'' is %1.3f\n',a);
|
The value of 'a' is 3.142 |
%% | Inserts a % sign | score = 0.75;
fprintf('Your score is %2.0f%%\n',100*score);
|
Your score is 75% |
Left Justifying Output
Be default, output is right-justified. To left-justify the output, insert a "-" sign between the % and the formatting string. For example,
Matlab Code | Output |
---|---|
fprintf('There were %10.1e people in %4.0f\n',2518629,1950);
Here the field width for the number of people is 10. The number width is less than that, so the output will be right-justified. |
There were 2.5e+06 people in 1950 |
fprintf('There were %-10.1e people in %4.0f\n',2518629,1950);
|
There were 2.5e+06 people in 1950 |
fprintf('%10s %10s\n','pi','sin(pi)'); % right justified
fprintf('--------------------\n');
fprintf('%10.5f %10.5f\n',pi,sin(pi)) % right justified
|
pi sin(pi) -------------------- 3.14159 0.00000 |
fprintf('\n%-10s %-10s\n','pi','sin(pi)'); % left justified
fprintf('--------------------\n');
fprintf('%-10.5f %-10.5f\n',pi,sin(pi)); % left justified
|
pi sin(pi) -------------------- 3.14159 0.00000 |
File Output
The fprintf command may be used to write formatted output to files. This requires three steps:
- Open the file for writing. Use the fopen command to open files.
- Write to the file using the fprintf command.
- Close the file using the fclose command.
Here is an example of writing data to a file.
Matlab Code | Contents of "myOutput.dat" |
---|---|
x = linspace(-pi,pi);
y = sin(x);
% step 1: open the file
out = fopen('myOutput.dat');
% step 2: write data to the file
fprintf(out,'%-10s %-10s\n','x','sin(x)');
for i=1:length(x)
fprintf(out,'%-10.5f %10.5f\n',x(i),y(i));
end
% step 3: close the file
fclose(out);
|
x sin(x) --------------------- -3.14159 -0.00000 -2.44346 -0.64279 -1.74533 -0.98481 -1.04720 -0.86603 -0.34907 -0.34202 0.34907 0.34202 1.04720 0.86603 1.74533 0.98481 2.44346 0.64279 3.14159 0.00000 |
Note that the file "myOutput.dat" will be saved in the directory where the script was run from.
Saving Variables with SAVE
The save command may be used to save any variables defined in Matlab to a file. You can then load this file back into Matlab and your variables will be defined. The basic syntax is:
save FILENAME; % save ALL variables to a file called "FILENAME.mat"
save FILENAME x1 x2 y; % save only x1 x2 and y to "FILENAME.mat"
. To load the file, use
load FILENAME;
For example:
clear;
a = rand(3);
b = 1:5:100;
c = {'Bob','Fred','Kerry','Jill'};
save myVars; % save all variables to the file "myVars.dat"
clear; % now no variables are defined.
load myVars; % loads the file myVariables.mat
who; % a, b, and c are defined again.
save myVars b c; % save only b and c.
clear; % now no variables are defined.
load myVars;
who; % b and c are defined. a is not.
|
Input in MATLAB
Input can be accomplished in several ways in Matlab:
- Interactive input from the user. This is accomplished using the input command.
- Reading files from disk. There are two common methods to do this: using fscanf command and using the load command.
The INPUT command
The basic syntax for the input command is:
x = input('text to command window');
|
This outputs the given text to the command window. The user can then enter a value and it will be stored in x.
The FSCANF command
There are three steps to read from a file:
- Open the file using fopen
- Read from the file using fscanf
- Close the file using fclose
The fscanf command is used primarily for reading from files. The basic syntax is:
value = fscanf( fid, format, size );
| ||||||||||||||
|
Opening and Closing Files
Before reading from a file, we must open it. This is done using the fopen command:
fid = fopen('filename','r'); % opens a file named "filename" for reading.
|
This assigns an identifier to fid that can be used in subsequent file operations (reading, closing, etc.). The 'r' indicates that this file is to be read from. Options are:
Flag | Description |
---|---|
'r' | Open a file for reading. |
'w' | Open a file for writing (creates the file if it doesn't already exist). An existing file will be overwritten. |
'a' | Open a file and append it (creates the file if it doesn't already exist). |
After you are done with a file, you should close it using the fclose command:
fclose(fid); % closes the file referred to be "fid"
|
A Simple Example
File "ages.dat" | Matlab Commands | Explanation |
---|---|---|
Fred 64 Bob 32 Julia 49 |
file = fopen('ages.dat','r');
name = fscanf( file, '%s', 1 );
age = fscanf( file, '%s' );
fclose(file);
|
Reads a string number into the variable name. Note the "1" at the end of this statement. If we didn't use "1" when reading the name, then it would have read the entire file into the string. After reading the name, we read the age into the variable age. |
If we wanted to read the whole file, we would need a few additional things:
- A cell array to hold the names
- An array to hold the ages.
- A way to determine when we hit the end of the file. This is done using the feof(fid) command.
Using these concepts, we can now read the file.
fid = fopen('ages.dat','r'); % opens the file "ages.dat" for reading.
i = 1;
names = {};
ages = [];
while ~feof(fid)
names{i} = fscanf(fid,'%s',1); % read the name.
age(i) = fscanf(fid,'%i'); % read the age.
i = i+1; % get ready to read the next line
end
fclose(fid); % close the file.
|