Appendix E:   Matlab


Under major construction


Matlab (short for matrix laboratory) is a specialized numerical computing environment and programming language. It has built-in support for manipulating matrices, complex numbers, and data visualization. It is widely used by scientists and engineers in industry and academia. Runs on most popular operating systems. Can use as a powerful calculator and data visualization tool. More importantly, you can program in Matlab. Can best exploit and appreciate Matlab after you've take a course in linear algebra. Here is an online tutorial.

Features.

Good for rapid prototyping and "programming in the small." Many modern programming features tacked on (cell arrays, structures, objects, nested functions, anonymous functions, function pointers, operator overloading), but esoteric and inconsistent notation. As a result many Matlab programmers never use them.

Availability.

It's proprietary commercial software distributed by The MathWorks. Many universities have a site license or laboratories where it is installed.

Hello World.

Matlab is not explicitly compiled. Interactive interpreter: enter commands in Command window (analogous to DrJava Interaction Pane) Save away a sequence of commands in a Script-M file (analogous to sequence of statements in main()).

Built-in types of data.

"Everything is an array". Matlab has 15 fundamental types: int8, uint8, int16, uint16, int32, uint32, int64, uint64, single, double, logical, char, cell, structure, and function handle. All of these are in the form of an array (from a minimum of 0-by-0 in size to d-dimensional array of any size). Can also access user defined types: user classes and Java classes. The default data type is a 2D array (or matrix) of doubles. Strings = char array (though to create an array of strings of different sizes, use a cell array).

In Matlab, complex numbers are doubles with a real part and an imaginary part. (Behind the scenes Matlab, stores 2 parallel double vectors, one for the real part and one for the imaginary part.) Good idea to set i = sqrt(-1) before using (since you may have changed the value of i earlier).

Representation is same as for Java. Floating point numbers use IEEE 754; integers are two's complement.

Scalar operators. +, -, *, / (floating point division), ^ (for exponentiation).

Note: use rem(17, 3) for integer remainder instead of %.

Comparison operators. < <= > >= == ~= (instead of !=). Returns a logical, which has the value 1 for true and 0 for false.

Boolean operators. &&, ||, ~ (instead of !)

Math library. sqrt(), rand(), pi, abs() The following illustrates how to do basic arithmetic calculations.

% matlab
format compact
>> besselk(1, -3)
ans =  -0.0402 -12.4199i

>> erf(0.9)
ans =   0.7969

Strings. String literal: 'hello' instead of "hello". String concatenation: a = ['hello' 'world']

Precedence order. Precedence order, parentheses, associativity.

Statements. Statements end with a semicolon; if you omit the semicolon you get an echo response.

Variables. Case-sensitive.

radius = 25.3;
area = pi * radius^2;

Dynamically typed. Java is strongly typed and statically typed. Every expression and variable has a type that is known (and checked) and compile-time. Matlab is dynamically typed. Variables declared without defining their types. The type is determined at runtime. Seems easier for programmer, but significantly more error-prone. When Matlab encounters a new variable, it automatically allocates the right amount of storage; when a variable changes, it re-allocates memory if necessary. Weakly typed (type of variable is not enforced, e.g., can concatenate string "12" and the integer 3 to get "123", then treat it as an integer, all without any explicit conversions). Matlab is very weakly typed.

a = 5;          % 1-by-1 double
a = [2 3 4];    % 1-by-3 double
a = 10 < 17;    % 1-by-1 logical
a = a + a;      % 1-by-1 double
class(a)
Disadvantage: errors not discovered until run-time. For example, the constant i is pre-defined as the square root of -1. However, you can redefine it to be an integer or an array. Or, if you name a variable the same name as a function, this will hide the function, making it impossible to call. Be careful!
min = 17;
min(rand(100, 1));  % error
class(a)
% awkward type checking

is leap year

if (round(year) ~= year))
    error('Year must be an integer.')
end

Conditionals and loops.

Conditionals: if statements are similar to Java.
if (x < 0)
   x = -x;
end

if (x > y)
   max = x;
else
   max = y;
end

if     (income <      0) rate = .00;
elseif (income <  47450) rate = .25;
elseif (income < 174700) rate = .28;
elseif (income < 311950) rate = .33;
else                     rate = .35;
end
Loops. While loop similar; for loop less expressive (can only iterate a variable over the elements of an array).
% print largest power of two less than or equal to N
v = 1;
while (v <= N/2)
   v = 2 * v
end
v

% compute a finite product N! = 1 * 2 * ... * N
product = 1;
for i = 1:N
   product = product * i;
end
product

% or more simply product = prod(1:N)

Arrays.

Vectors and matrices.

Creating vectors and matrices. (linspace, colon, ones, zeros, rand).

A = [ 1 2 3; 4 5 6 ];     % 2-by-3 matrix
B = [ 1 2; 3 4; 5 6 ];    % 3-by-2 matrix
x = [ 1 2 3 ];            % row vector
y = [ 1; 2; 3 ];          % column vector

A = rand(3, 4);           % random 3-by-4 matrix
y = zeros(1, 10);         % length 10 row vector of all zeros
x = 1:10;                 % length 10 vector of 1, 2, ..., 10
z = linspace(0, 10, 100); %  length 100 vector of values evenly between 0 and 10

Matrix and vector operations. Indexing: use a(i) to access ith element. Java is 0-based; Matlab is 1-based indexing. Subarray and submatrices using colon notation.

Vector operations: most functions work with vector arguments. Also mean(), min(), max(), std(), median().

% plot sinc function = sin x / x, from pi/100 to 10pi
x = pi/100 : pi/100 : 10*pi;
% x = linspace(pi/100, 10*pi, 1000);
y = sin(x) ./ x; 
plot(x, y) 

Matrix scaling, addition, multiplication, transpose, element-by-element arithmetic.

Vectorization. Prior to Matlab 6.5, very costly to perform loops. JIT-Accelerator improved performance by orders of magnitude. Must pre-allocate memory before loop. x = linspace(0, 2*pi, N); y = sin(x); vs. x = 0; y = zeros(1, N); for i = 1:N y(i) = sin(2 * pi * (i-1) / N); end

Input and output.

x = input('Enter a value\n');
Enter a value
3.14
printf printing System.out.println("Hello") disp('Hello') formatted printing System.out.printf("%8.4f\n", x) fprintf('%8.4f\n', x)

Functions.

Matlab provides many built-in functions. As in Java, Matlab cannot include ever function that you might need. Accordingly, you can implement your own functions using M-file functions. Function has same name as the M-file.

Like Java, M-file functions can have any number of input arguments. Unlike Java, they can also have any number of output arguments.

% keyword, output argument, function name, input arguments
function c = hypotenuse(a, b) 
c = sqrt(a*a + b*b);  
Can return multiple values from a function.
function [c, d] = f(a, b)    % multiple output arguments
function g(a, b)             % no output arguments
Overloading. Annoying to support two functions with the same name, but different signatures. Here's a hack.
function y = phi(x, mu, sigma)
   if nargin == 1
       y = exp(-x.^2 / 2) / sqrt(2 * pi);       
   else
       y = exp(-((x-mu)/sigma).^2 / 2) / sqrt(2 * pi * sigma);       
end
(Matlab does have class directories where you put different overloaded functions by putting in separate subdirectories named \@int32 and \@double.)

Sound waves. Matlab especially suited to signal processing.

function a = note(pitch, duration)
   hz = 440 * 2^(pitch / 12);
   mid = tone(1.0*hz, duration);
   hi  = tone(2.0*hz, duration);
   lo  = tone(0.5*hz, duration);
   a = .5*mid + .25*hi + .25*lo;
end

function a = tone(hz, duration)
   SAMPLES_PER_SECOND = 44100;
   N = floor(SAMPLES_PER_SECOND * duration);
   i = 0:N;
   a = sin (2 * pi * i * hz / SAMPLES_PER_SECOND);
end
Then, to play a note:
plot(note(0, .005));
sound(note(0, 1), 44100);

Pass by value. When you call a function (or make an assignment) the arguments get copied. If you modify the argument within the function, you are modifying a copy of the argument local to the function. To modify variables from wtihin a function you need to return the result when finished.

x = f(x);
Matlab uses a scheme called copy on write to optimize when you pass a big array to a function, it only copies it if you modify one of the variables. Thus, you can freely pass large arrays to functions without worrying about overhead (provided you don't change them).

But watch out if you pass large arrays and then modify the variables. Swap function very ineffcient. The following function takes time and space proportional to the length of the vector x. Matlab is consistently pass-by-value, so if a function modifies an array, it must return the result via output parameters.

function x = swap(x, i, j)
%SWAP  Swap elements i and j in vector x
%   x = swap(x, i, j) swap elements i and j in array x

x([i j]) = x([j i]);
end
function x = shuffle(x)
%SHUFFLE  Shuffle an array of values.
%   x = shuffle(x) shuffles the vector x in random order.

%   Since this function changes the vector x,
%   it creates a copy of it.

n = length(x);
disp n
for index = 1:n

    % a random number between i and n
    r = index + floor((n-index+1) * rand());
    
    % swap elements index and r
    x([index r]) = x([r index]);
end

Subfunctions. Can include a helper function in the same M-file as the primary function. In Matlab, these are called subfunctions. They cannot be called directly from outside the M-file, e.g., private. Only the first function defined in a file is public.

Caveat: y = f(x) can be either a function call or an array access, depending on context.

Recursion.

Recursion is fully supported.
function d = mygcd(x, y)
%MYGCD  Return the gcd of two integers.
%   d = gcd(x, y) returns the greatest common divisor
%   of x and y.

% awkward type checking
if (round(x) ~=x) || (round(y) ~=y)
    error('Requires integer input arguments.')
end


% Euclid's algorithm
if y == 0
    d = x;
else
    d = mygcd(y, rem(x, y));
end

- local vs $global$ variables (scope) - $error$, $warning$ - nested functions

Libraries.

A key feature of Matlab is its extensive numerical libraries. Image processing, optimization, ....

Rich libraries for scientific computing: besselj(), gcd(),

Each M-function file can only have one function visible to the outside world. Results in a surfeit of files. Matlab programmers can organize a bunch of related M-files into a toolbox, which basically amounts to storing lots of files in the same directory.

Linear algebra.

In Matlab, the primary data type is a complex matrix. A scalar is a 1-by-1 matrix; a vector is a 1-by-N or N-by-1 matrix. The following illustrates how to solve systems of linear equations with the \ operator. When the system is over-determined, the result is a least squares solution. (See section xyz.)
>> A = [0, 1, 1; 2, 4, -2; 0, 3, 15]
A =  0     1     1
     2     4    -2
     0     3    15

>> b = [4; 2; 36]
b =  4
     2
    36

>> x = A \ b
x = -1
     2
     2

>> A * x
ans = 4.0000
      2.0000
     36.0000

One of the most powerful features of Matlab is its extensive numerical linear algebra library.

>> cond(A)
ans = 58.8670

>> eig(A)
ans =  13.5765
       -0.6419
        2.0654

>> [Q R] = qr(A)
Q =  -0.1078    0.5683   -0.8157
     -0.6470   -0.6631   -0.3765
     -0.7548    0.4872    0.4392

R =  -9.2736   -9.4893   -7.7640
           0    1.7186    5.4264
           0         0    1.1294

>> svd(A)
ans =  15.8836
        4.2000
        0.2698

Matlab Libraries.

Matlab also has numerous libraries geared toward scientific and commercial applications including: solving systems of ODEs, signal processing, wavelets, equation solving, linear and nonlinear optimization, neural networks, image processing, interpolation, polynomials, data analysis, Fourier transforms, elementary and special mathematical functions, and digital audio. Matlab tutorial Also string libraries including regular expressions.

Programming in Matlab. Loops, conditionals, functions, building re-usable libraries, function handles, data types (8, 16, 32- bit integers, multi-dimensional arrays, strings, struct). MATLAB includes OOP features, including classes and objects, operator overloading, inheritance, although it is fairly well hidden. It is even possible to call Java from Matlab. However, Matalb does not support passing arguments by reference (pointers).

All objects are immutable - to "change" an object, you need to pass the object as an input argument and return a new object with the data changed. Private helper methods are implemented by putting the methods in a subdirectory named private. Matlab supports operator overloading. use display method as analog of toString(). Use subsref to overload subscripted reference, plus, minus, mtimes, for addition, subtraction, and multiplication.

Objects.

Awkward and rarely used in practice.

Function functions. Functions handles are data types in Matlab. Can pass functions to other functions (feval, eval, fzero, ezplot).

Data structures.

No support for references or pointers. Difficult to implement linked structures.

Integration with Java.

Matlab is tightly integrated with Java - the Matlab interpreter is written in Java. Can directly call Java code.
s = java.lang.String('hello, world')
s = s.replaceAll('l', 'abc')


Concept                    Java                               Matlab
---------------------------------------------------------------------

Comments (single line)     // single-line commment            % single line comment
Comment (multi-line)       /* multi-line comment */           %{ multi-line comment %}

regular expressions        indexOf(), replaceAll()            regexp()

array of strings           String[]                           need to use cell array (unless strings are of same length)

+ strings
  - characters as ASCII codes
  - converting 
  - num2str, str2num
  - comparing strings
  - concatenating strings
  - $double$, $char$