Wednesday, 9 February 2011

Data Files (Matlab tutorial)

Data Files

Matlab does not allow you to save the commands that you have entered in a session, but it does allow a number of different ways to save the data. In this tutorial we explore the different ways that you can save and read data into a Matlab session.
  1. Saving and Recalling Data
  2. Saving a Session as Text
  3. C Style Read/Write

Saving and Recalling Data

As you work through a session you generate vectors and matrices. The next question is how do you save your work? Here we focus on how to save and recall data from a Matlab session. The command to save all of the data in a session is save. The command to bring the data set in a data file back into a session isload.
We first look at the save command. In the example below we use the most basic form which will save all of the data present in a session. Here we save all of the data in a file called "stuff.mat." (.mat is the default extension for Matlab data.)
>> u = [1 3 -4];
 >> v = [2 -1 7];
 >> whos
   Name      Size                    Bytes  Class

   u         1x3                        24  double array
   v         1x3                        24  double array

 Grand total is 6 elements using 48 bytes

 >> save stuff.mat
 >> ls
 stuff.mat
 
The ls command is used to list all of the files in the current directory. In this situation we created a file called "stuff.mat" which contains the vectors u and v. The data can be read back in to a Matlab session with the load command.
>> clear
 >> whos
 >> load stuff.mat
 >> whos
   Name      Size                    Bytes  Class

   u         1x3                        24  double array
   v         1x3                        24  double array

 Grand total is 6 elements using 48 bytes

 >> u+v

 ans =

      3     2     3
 
In this example the current data space is cleared of all variables. The contents of the entire data file, "stuff.mat," is then read back into memory. You do not have to load all of the contents of the file into memory. After you specify the file name you then list the variables that you want to load separated by spaces. In the following example only the variable u will be loaded into memory.
>> clear
 >> whos
 >> load stuff.mat u
 >> whos
   Name      Size                    Bytes  Class

   u         1x3                        24  double array

 Grand total is 3 elements using 24 bytes

 >> u

 u =

      1     3    -4
 
Note that the save command works in exactly the same way. If you only want to save a couple of variables you list the variables you want to save after the file name. Again, the variables must be separated by a space. For an example and more details please see the help file for save. When in matlab just type in help save to see more information. You will find that there are large number of options in terms of how the data can be saved and the format of the data file.

Saving a Session as Text

Matlab allows you to save the data generated in a session, but you cannot easily save the commands so that they can be used in an executable file. You can save a copy of what happened in a session using the diary command. This is very useful if you want to save a session for a homework assignment or as a way to take notes.
A diary of a session is initiated with the diary command followed by the file name that you want to keep the text file. You then type in all of the necessary commands. When you are done enter the diary command alone, and it will write all of the output to the file and close the file. In the example below a file called "save.txt" is created that will contain a copy of the session.
>> diary save.txt
  ... enter commands here...
 >> diary
 
This will create a file called "save.txt" which will hold an exact copy of the output from your session. This is how I generated the files used in these tutorials.

C Style Read/Write

In addition to the high level read/write commands detailed above, Matlab allows C style file access. This is extremely helpful since the output generated by many home grown programs is in binary format due to disk space considerations. This is an advanced subject, and we do not go into great detail here. Instead we look at the basic commands. After looking at this overview we highly recommend that you look through the relevant help files. This will help fill in the missing blanks.
The basic idea is that you open a file, execute the relevant reads and writes on a file, and then close a file. One other common task is to move the file pointer to point to a particular place in the file, and there are two commands, fseek and ftell to help.
Here we give a very simple example. In the example, a file called "laser.dat" is opened. The file identifier is kept track of using a variable called fp. Once the file is opened the file position is moved to a particular place in the file, denoted pos, and two double precision numbers are read. Once that is done the position within the file is stored, and the file is closed.
fp = fopen('laser.dat','r');
 fseek(fp,pos,'bof');
 tmp = fread(fp,2,'double');
 pos = ftell(fp);
 fclose(fp);
 

The If Statement(matlab tutorial)

The If Statement

In this tutorial we will assume that you know how to create vectors and matrices, know how to index into them, and know about loops. For more information on those topics see one of our tutorials on vectors, matrices, vector operations, loops, plotting, executable files, or subroutines.
There are times when you want your code to make a decision. For example, if you are approximating a differential equation, and the rate of change is discontinuous, you may want to change the rate depending on what time step you are on.
Here we will define an executable file that contains an if statement. The file is called by Matlab, and it constructs a second derivative finite difference matrix with boundary conditions. There is a variable in the file called decision. If this variable is less than 3, the file will find and plot the eigen values of the matrix, if it is greater than 3 the eigen values of the inverse of the matrix are found and plotted, otherwise, the system is inverted to find an approximation to y'=sin(x) according to the specified boundary conditions.

There are times when you want certain parts of your program to be executed only in limited circumstances. The way to do that is to put the code within an "if" statement. The most basic structure for an "if" statement is the following:
if  (condition statement)
    (matlab commands)
end
More complicated structures are also possible including combinations like the following:
if  (condition statement)
    (matlab commands)
elseif  (condition statement)
    (matlab commands)
elseif (condition statement)
    (matlab commands)
.
.
.
else
    (matlab commands)
end

The conditions are boolean statements and the standard comparisons can be made. Valid comparisons include "<" (less than), ">" (greater than), "<=" (less than or equal), ">=" (greater than or equal), "==" (equal - this is two equal signs with no spaces betweeen them), and "˜=" (not equal). For example, the following code will set the variable j to be -1:
a = 2;
b = 3;
if (a<b) 
    j = -1;
end 

Additional statements can be added for more refined decision making. The following code sets the variable j to be 2.
a = 4;
b = 3;
if (a<b) 
    j = -1;
elseif (a>b)
    j = 2;
end 

The else statement provides a catch all that will be executed if no other condition is met. The following code sets the variable j to be 3.
a = 4;
b = 4;
if (a<b) 
    j = -1;
elseif (a>b)
    j = 2;
else 
 j = 3
end 
This last example demonstrates one of the bad habits that Matlab allows you to get away with. With finite precision arithmetic two variables are rarely exactly the same. When using C or FORTRAN you should never compare two floating numbers to see if they are the same. Instead you should check to see if they are close. Matlab does not use integer arithmetic so if you check to see if two numbers are the same it automatically checks to see if the variables are close. If you were to use C or FORTRAN then that last example could get you into big trouble. but Matlab does the checking for you in case the numbers are just really close.

Matlab allows you to string together multiple boolean expressions using the standard logic operators, "&" (and), ¦ (or), and ˜ (not). For example to check to see if a is less than b and at the same time b is greater than or equal to c you would use the following commands:
if (a < b) & (b >= c) 
   Matlab commands
end


Example

If you are not familiar with creating exectable files see our tutorial on the subject. Otherwise, copy the following script into a file called ifDemo.m.
decision = 3;
leftx = 0;
rightx = 1;

lefty = 1;
righty = 1;

N= 10;
h = (rightx-leftx)/(N-1);
x = [leftx:h:rightx]';

A = zeros(N);

for i=2:N-1,
   A(i,i-1:i+1) = [1 -2 1];
end

A = A/h^2;

A(1,1) = 1;
A(N,N) = 1;

b = sin(x);
b(1) = lefty;
b(N) = righty;

if(decision<3)

    % Find and plot the eigen values
    [e,v] = eig(A);
    e = diag(e);
    plot(real(e),imag(e),'rx');
    title('Eigen Values of the matrix');

elseif(decision>3)

    % Find and plot the eigen values of inv(A)
    [e,v] = eig(inv(A));
    e = diag(e);
    plot(real(e),imag(e),'rx');
    title('Eigen Values of the inverse of the matrix');

else

   
    % Solve the system
    y = A\b;
    linear = (lefty-righty+sin(leftx)-sin(rightx))/(leftx-rightx);
    constant = lefty + sin(leftx) - linear*leftx;
    true = -sin(x) + linear*x + constant;

    subplot(1,2,1);
    plot(x,y,'go',x,true,'y');
    title('True Solution and Approximation');
    xlabel('x');
    ylabel('y');
    subplot(1,2,2);
    plot(x,abs(y-true),'cx');
    title('Error');
    xlabel('x');
    ylabel('|Error|');


end



You can execute the instructions in the file by simply typing ifDemo at the matlab prompt. Try changing the value of the variable decision to see what actions the script will take. Also, try changing the other variables and experiment.
The basic form of the if-block is demonstrated in the program above. You are not required to have an elseif or else block, but you are required to end the if-block with the endif statement.

Subroutines in matlab

Subroutines

In this tutorial we will assume that you know how to create vectors and matrices, know how to index into them, and know about loops. For more information on those topics see one of our tutorials on vectors, matrices, vector operations, loops, plotting, or executable files.
Sometimes you want to repeat a sequence of commands, but you want to be able to do so with different vectors and matrices. One way to make this easier is through the use of subroutines. Subroutines are just like executable files, but you can pass it different vectors and matrices to use.
For example, suppose you want a subroutine to perform Gaussian elimination, and you want to be able to pass the matrix and pass the vector (This example comes from the tutorial on loops). The first line in the file has to tell matlab what variables it will pass back when and done, and what variables it needs to work with. Here we will try to find x given that Ax=b.
The routine needs the matrix A and the vector B, and it will pass back the vector x. If the name of the file is called gaussElim.m, then the first line will look like this: 
function [x] = gaussElim(A,b)
If you want to pass back more than one variable, you can include the list in the brackets with commas in between the variable names (see the second example). If you do not know how to create a file see our tutorial on executable files.

Here is a sample listing of the file gaussElim.m:
function [x] = gaussElim(A,b)
% File gaussElim.m
%   This subroutine will perform Gaussian elmination
%   on the matrix that you pass to it.
%   i.e., given A and b it can be used to find x,
%        Ax = b
%
%   To run this file you will need to specify several
%   things:
%   A - matrix for the left hand side.
%   b - vector for the right hand side
%
%   The routine will return the vector x.
%   ex: [x] = gaussElim(A,b)
%     this will perform Gaussian elminiation to find x.
%
%


 N = max(size(A));


% Perform Gaussian Elimination

 for j=2:N,
     for i=j:N,
        m = A(i,j-1)/A(j-1,j-1);
        A(i,:) = A(i,:) - A(j-1,:)*m;
        b(i) = b(i) - m*b(j-1);
     end
 end

% Perform back substitution

 x = zeros(N,1);
 x(N) = b(N)/A(N,N);

 for j=N-1:-1:1,
   x(j) = (b(j)-A(j,j+1:N)*x(j+1:N))/A(j,j);
 end



To get the vector x, you simply call the routine by name. For example, you could do the following:
>> A = [1 2 3 6; 4 3 2 3; 9 9 1 -2; 4 2 2 1]

A =

     1     2     3     6
     4     3     2     3
     9     9     1    -2
     4     2     2     1

>> b = [1 2 1 4]'

b =

     1
     2
     1
     4

>> [x] = gaussElim(A,b)


x =

    0.6809
   -0.8936
    1.8085
   -0.5532

>> 
Sometimes you want your routine to call another routine that you specify. For example, here we will demonstrate a subroutine that will approximate a D.E., y'=f(x,y), using Euler's Method. The subroutine is able to call a function, f(x,y), specified by you.
Here a subroutine is defined that will approximate a D.E. using Euler's method. If you do not know how to create a file see our tutorial on executable files.

Here is a sample listing of the file eulerApprox.m:
function [x,y] = eulerApprox(startx,h,endx,starty,func)
% file: eulerApprox.m
% This matlab subroutine will find the approximation to
%  a D.E. given by 
%     y' = func(x,y)
%     y(startx) = starty
%
%  To run this file you will first need to specify
%  the following:
%      startx  : the starting value for x
%      h       : the step size
%      endx    : the ending value for x
%      starty  : the initial value
%      func    : routine name to calculate the right hand 
%                side of the D.E..  This must be specified
%                as a string.
%
%   ex: [x,y] = eulerApprox(0,1,1/16,1,'f');
%       Will return the approximation of a D.E.
%       where x is from 0 to 1 in steps of 1/16.
%       The initial value is 1, and the right hand
%       side is calculated in a subroutine given by
%       f.m.
%
%  The routine will generate two vectors.  The first
%  vector is x which is the grid points starting at
%  x0=0 and have a step size h.  
%
%  The second vector is an approximation to the specified
%  D.E. 
%



x = [startx:h:endx];

y = 0*x;
y(1) = starty;

for i=2:max(size(y)),
   y(i) = y(i-1) + h*feval(func,x(i-1),y(i-1));
end


In this example, we will approximate the D.E. y'=1/y. To do this you will have to create a file called f.m with the following commands:
function [f] = f(x,y)
% Evaluation of right hand side of a differential
% equation.  

f = 1/y;


With the subroutine defined, you can call it whenever necessary. Note that when you put comments on the 2nd line, it acts as a help file. Also note that the function f.m must be specified as a string, 'f'.
>> help eulerApprox

  file: eulerApprox.m
  This matlab subroutine will find the approximation to
   a D.E. given by 
      y' = func(x,y)
      y(startx) = starty
 
   To run this file you will first need to specify
   the following:
       startx  : the starting value for x
       h       : the step size
       endx    : the ending value for x
       starty  : the initial value
       func    : routine name to calculate the right hand 
                 side of the D.E..  This must be specified
                 as a string.
 
    ex: [x,y] = eulerApprox(0,1,1/16,1,'f');
        Will return the approximation of a D.E.
        where x is from 0 to 1 in steps of 1/16.
        The initial value is 1, and the right hand
        side is calculated in a subroutine given by
        f.m.
 
   The routine will generate two vectors.  The first
   vector is x which is the grid points starting at
   x0=0 and have a step size h.  
 
   The second vector is an approximation to the specified
   D.E. 
 

>> [x,y] = eulerApprox(0,1/16,1,1,'f');
>> plot(x,y)
When the subroutine is done, it returns two vectors and stores them in x and y.

LinkWithin

Related Posts Plugin for WordPress, Blogger...