Difference between revisions of "Matlab IO"

From Sutherland_wiki
Jump to: navigation, search
(Terminal and File Output in MATLAB)
Line 132: Line 132:
  
  
== Terminal and File Output in MATLAB ==
+
== Output in MATLAB ==
{{Stub|section}}
 
  
 
=== DISP ===
 
=== 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>
 +
 +
 
=== FPRINTF ===
 
=== FPRINTF ===
==== File Output ====
+
 
 +
The '''<tt>fprintf</tt>''' command provides significantly more control over output.  The basic usage of this command is:
 +
<source lang="matlab">
 +
fprintf( fid, 'formatting & text', v1, v2, ... vn );
 +
</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 is controlled by the [[#Formatting_Output|formatting string]].
 +
 
 +
==== Formatting Output ====
 +
 
 +
{| border="1" cellpadding="5" cellspacing="0"
 +
|+ '''Control Characters for Output Formatting'''
 +
|- style="background:lightgrey"
 +
! Control Code !! Description !! Example
 +
|-
 +
| <tt>\n</tt> || New Line
 +
|<source lang="matlab">
 +
fprintf('Hello,\nWorld\n');
 +
</source>
 +
|-
 +
| <tt>\t</tt> || A Tab character (useful for spacing)
 +
|<source lang="matlab">
 +
fprintf('\tline 1 \n line 2\n');
 +
</source>
 +
|-
 +
| <tt>\\</tt> || Inserts a backslash
 +
|<source lang="matlab">
 +
fprintf('Here is a backslash: \\');
 +
fprintf('A backslash: \\\nand then a new line\n');
 +
</source>
 +
|-
 +
| <tt>''</tt> || Inserts a single quote
 +
|<source lang="matlab">
 +
a = pi;
 +
fprintf('The value of ''a'' is %1.3f\n',a);
 +
</source>
 +
|-
 +
| <tt>%%</tt> || Inserts a % sign
 +
|<source lang="matlab">
 +
score = 0.75;
 +
fprintf('Your score is %2.0f%%\n',100*score);
 +
</source>
 +
|}
 +
 
 +
 
 +
{| border="1" cellpadding="5" cellspacing="0"
 +
|+ '''Variable formatting'''
 +
|-
 +
| <tt>f</tt> || Floating point (decimal) format
 +
|<source lang="matlab">
 +
fprintf('The value of pi to 6 decimal places is: %1.6f\n',pi);
 +
</source>
 +
|-
 +
| <tt>e</tt> || Scientific Notation
 +
|<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]
 +
|-
 +
| <tt>s</tt> || String output
 +
|<source lang="matlab">
 +
names = {'Bob','Jill','Carl','Steve'};
 +
for i=1:length(names)
 +
  fprintf('%s\n',names{i});
 +
end
 +
</source>
 +
|}
 +
 
 +
 
 +
==== 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,
 +
{| border="1" cellpadding="5" cellspacing="0"
 +
|- style="background:lightgrey"
 +
! Matlab Code !! Output
 +
|-
 +
|<source lang="matlab">
 +
fprintf('There were %10.1e people in %4.0f\n',2518629,1950);
 +
</source>
 +
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.
 +
|<pre>There were    2.5e+06 people in 1950</pre>
 +
|-
 +
|<source lang="matlab">
 +
fprintf('There were %-10.1e people in %4.0f\n',2518629,1950);
 +
</source>
 +
| <pre>There were 2.5e+06    people in 1950</pre>
 +
|-
 +
|<source lang="matlab">
 +
fprintf('%10s %10s\n','pi','sin(pi)');      % right justified
 +
fprintf('--------------------\n');
 +
fprintf('%10.5f %10.5f\n',pi,sin(pi))      % right justified
 +
</source>
 +
|<pre>
 +
        pi    sin(pi)
 +
--------------------
 +
  3.14159    0.00000
 +
</pre>
 +
|-
 +
|<source lang="matlab">
 +
fprintf('\n%-10s %-10s\n','pi','sin(pi)');  % left justified
 +
fprintf('--------------------\n');
 +
fprintf('%-10.5f %-10.5f\n',pi,sin(pi));    % left justified
 +
</source>
 +
|<pre>
 +
pi        sin(pi) 
 +
--------------------
 +
3.14159    0.00000 
 +
</pre>
 +
|}
 +
 
 +
 
 +
 
 +
=== File Output ===
 +
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.
 +
# Write to the file using the [[#fprintf|'''<tt>fprintf</tt>''' command]].
 +
# Close the file using the '''<tt>fclose</tt>''' command.
 +
 
 +
Here is an example of writing data to a file.
 +
{| border="1" cellpadding="5" cellspacing="0"
 +
|- style="background:lightgrey"
 +
! Matlab Code !! Contents of "myOutput.dat"
 +
|- valign="top"
 +
|<source lang="matlab">
 +
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);
 +
</source>
 +
|<pre>
 +
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
 +
</pre>
 +
|}
 +
 
 +
Note that the file "myOutput.dat" will be saved in the directory where the script was run from.
 +
 
  
 
=== Saving Variables with SAVE ===
 
=== Saving Variables with SAVE ===
 
+
{{Stub|section}}
  
 
== Exporting Matlab Figures ==
 
== Exporting Matlab Figures ==
 
{{Stub|section}}
 
{{Stub|section}}

Revision as of 12:25, 22 September 2008

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('Enter the value of x: ');

This outputs the given text to the command window. The user can then enter a value and it will be stored in x.


Loading variables using LOAD

Warn.jpg
This section is a stub and needs to be expanded.
If you can provide information or finish this section you're welcome to do so and then remove this message afterwards.


The FSCANF command

There are three steps to read from a file:

  1. Open the file using fopen
  2. Read from the file using fscanf
  3. Close the file using fclose

The fscanf command is used primarily for reading from files. The basic syntax is:

value = fscanf( fid, format, size );
fid The identifier for the file to read from. This is obtained using the fopen command.
format A text string indicating the format to use when reading values from the file. This is of the form %Na, where N specifies the width to read and f specifies the format to read.
%c Reads a character (e.g. "q")
%s Reads a character string (e.g. "quiet")
%d Reads an integer (e.g. 12345)
%f Reads a floating point number (e.g. 5.62)
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:
  • N - read at most N entries from the file.
  • inf - read at most to the end of the file.
  • [M,N] - read M*N entries from the file and arrange them into an M x N matrix.


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:

Flags for fopen
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.


Output in MATLAB

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 );


FPRINTF

The fprintf command provides significantly more control over output. The basic usage of this command is:

fprintf( fid, 'formatting & text', v1, v2, ... vn );

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.

Formatting Output

Control Characters for Output Formatting
Control Code Description Example
\n New Line
fprintf('Hello,\nWorld\n');
\t A Tab character (useful for spacing)
fprintf('\tline 1 \n line 2\n');
\\ Inserts a backslash
fprintf('Here is a backslash: \\');
fprintf('A backslash: \\\nand then a new line\n');
Inserts a single quote
a = pi;
fprintf('The value of ''a'' is %1.3f\n',a);
%% Inserts a % sign
score = 0.75;
fprintf('Your score is %2.0f%%\n',100*score);


Variable formatting
f Floating point (decimal) format
fprintf('The value of pi to 6 decimal places is: %1.6f\n',pi);
e Scientific Notation
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]

s String output
names = {'Bob','Jill','Carl','Steve'};
for i=1:length(names)
  fprintf('%s\n',names{i});
end


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:

  1. Open the file for writing. Use the fopen command to open files.
  2. Write to the file using the fprintf command.
  3. 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

Warn.jpg
This section is a stub and needs to be expanded.
If you can provide information or finish this section you're welcome to do so and then remove this message afterwards.

Exporting Matlab Figures

Warn.jpg
This section is a stub and needs to be expanded.
If you can provide information or finish this section you're welcome to do so and then remove this message afterwards.