Getting Started with MATLAB
   

Entering Matrices
 
You can enter matrices into MATLAB in several different ways.

 

 Start by entering above matrix as a list of its elements. You have only to follow a few basic conventions:

 » A = [1 2 3; 4 5 6; 7 8 9]

 MATLAB displays the matrix you just entered,

 A =

    1 2 3

    4 5 6

    7 8 9

 
Once you have entered the matrix, it is automatically remembered in the MATLAB workspace.

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(3,2) is the number in the third row and second column

A(3,2)

For the column vector b = [1; 2; 3] or row vector b = [1 2 3], b(2) is the number in the second entry.

Back to top

Generating Matrices

 MATLAB provides four functions that generate basic matrices:

 zeros             All zeros

ones                All ones

rand                 Uniformly distributed random elements

randn             Normally distributed random elements

Some examples:

 » Z = zeros(2,4)

Z =

    0 0 0 0

    0 0 0 0

» F = 5*ones(3,3)

F =

    5 5 5

    5 5 5

    5 5 5

 Back to top

 Sum and Transpose

 
To compute the sums of the columns of A=, enter

 » sum(A)

MATLAB replies with

ans =

    12 15 18

When you don't specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of a calculation.

The transpose operation is denoted by an apostrophe or single quote, '.

» A'

produces

ans =

    1 4 7

    2 5 8

    3 6 9

Back to top

 Arithmetic Operators

  +,  -,  *,  /,  and ^ for plus, minus, matrix multiply, right matrix divide, and matrix power.

Try following commands.

 » A+A

» A*A

» A^2

» 2*A

» A/2

» A+2

Back to top

 
Scripts and Functions

MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command.

There are two kinds of M-files:

 If you're a new MATLAB programmer, just create the M-files that you want to try out in the current directory. Or change the path. Suppose that your M-files are on the floppy disk drive A, we can change the current working directory by entering

» cd A:

Scripts

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations.

The following two examples illustrate for loops.

Example 1: Display the squares of the numbers from 1 to 5. Use the MATLAB editor to create an M-file with the following commands:

for k = 1:5

    A (k) = k^2;

end

A

Note that a semicolon, ; , is used after a command to suppress echo. Then save the file as example1.m.
In the MATLAB command window, type

»example1

MATLAB displays

A =

    1 4 9 16 25

Example 2: Find the sum of all even integers from 1 to 100.

s = 0;

for i =2:2:100
    s = s + i;
end
s
 

Functions

Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

Example 3: Define a piecewise function  if if , and if  using an M-file.

function y = f(x)

% define a piecewise function
if x < 0
    y = x^2;
  elseif  (0 <= x) & (x <= 2)
    y = 2*x+1;
  else
    y = 10;
end
return
 

Try following  in the MATLAB command window:

»f(-2)

»f(1)

»f(4)
 

In above example we used if statement, relational operators, and a Logical operator. The general form
of the if statement is

IF expression
    statements
ELSEIF expression
    statements
ELSE
    statements
END

Relational operators

Equal                             = =

Not equal                       ~ =

Less than                         <

Greater than                     >

Less than or equal          <=

Greater than or equal     >=
 
Logical Operators

Logical AND                        &

Logical OR                             |

Logical NOT                        ~
 
Back to top

While Loops
 
WHILE expression
        statements
END

The expression is usually in the form of

(expression)  (relation operator)  (expression)

where relation operator is one of ==, <, >, <=, >=, and ~=. The statements are executed while the expression is true.

Example 4: Redo example 2 with a while loop.

s = 0;
k = 2;
while k <= 100
    s = s + k;
    k = k + 2;
end
s

Back to top

BREAK Statement

The BREAK statement can be used to terminate the loop prematurely.

Example 5: Define a function to decide whether a number is a prime number.

function prime(n)

% n>3     input number to be determined whether it is prime.
% REM     Remainder after division. EX: rem(4,2)=0
% FLOOR   floor(x) gives the largest integer <= x.

half_n = floor(n/2);
for k = 2:half_n
    if rem(n,k)== 0
        'It is not prime; divisible by', k
        break
    end
end

if k >= half_n
    'it is prime'
end

return

Back to top

Functions with More Input and Output Variables (Matrices)

Example 6: Create a function that evaluates f(x) + b for a function f(x) and some number b at a variety of x-values and then sums those values. The function returns the number of the x-values, the function values f(x) + b , and the sum.

function [N,F,s]=sum_func(x,b)

% x     input one-dimension array of numbers
% b     an input number
% N     the number of function values
% F     one-dimension array of function values at the input x
% s     sum of those function values

% The length function finds the number of entries in x
N = length(x);

% Evaluate f(x) at each entry of x and add b. Then create an array F
for i = 1:N
    F(i) = f(x(i)) + b ;
end

% Find the sum of those function values
s = sum(F);

return
 

If we use the function f(x) defined in example 3 and x=[ –2 –1 0 1 2 3], we enter following commands in MATLAB command windows:

» x = -2:3;
» [N,F,s]=sum_func(x,3);
» N, F, s

MATLAB produces

N =

     6
 

F =

     7     4     4     6     8    13
 

s =

    42
 
Back to top

Plotting a function or data pairs

The following commands plot sin(x) on .

» x=0:0.1:2*pi;
» y=sin(x);
» plot(x,y)

The following commands plot  on [-2,2].

» x=-2:0.1:2;
» y=x.^2;
» plot(x, y)
» plot(x, y, 'o')
» plot(x, y,'b-', x, y, 'ro')

The last command plots the data twice, with a solid blue line interpolating red circles at the data points.

Try
»help plot
to see other uses of  the plot command.

You used the array power .^  in above example which calculates the power of each entry in a matrix.
If x = [1 2 3], x*x or x^3 does not make any sense. But

x.*x = [1 4 9] and x.^3 = [ 1 8 27].

Back to top

Arithmetic operators with period "." :

Array multiply                    .*                 See above example

Array power                       .^                 See above example

Left array divide                 .\                 Example:  x = [1 4 6], a = [1 2 3],  x./a =[1.0000    0.5000    0.5000]

Right array divide                ./                Example:   x = [1 4 6], a = [1 2 3], x./a = [1 2 2]
 

Help Commands

The following commands are useful when you look for the syntax of a MATLAB command.

help, helpwin, helpdesk, lookfor, tour, demo

For example, try

»helpwin

to learn all other MATLAB commands.

Back to top