Up Next
Go up to 2 Starting with MATLAB
Go forward to 2.2 Obtaining Help from MATLAB

2.1 Basic Use of MATLAB

MATLAB is designed to work easily with matrices and vectors, and a number of methods exist to declare matrices and vectors. For example, an entire matrix can be entered on one line with rows separated by semicolons (;):

>> A=[1 3 2;-1 0 9]
A =
     1     3     2
    -1     0     9
 

The matrix can also be typed in row by row:

>> A=[ 1 3        2
      -1      0            9] 
A =
     1     3     2
    -1     0     9
Notice that the spacing used has no effect. The transpose of a matrix can be found using the quote symbol ('):
>> B=[0 3 ;3 4;6 6];
>> B' 
ans =
     0     3     6
     3     4     6
The semicolon (;) at the end of a line stops MATLAB from displaying the answer on the screen. Basic matrix operations can be performed:
>> A+B
??? Error using ==> +
Matrix dimensions must agree.
>> A+B'
ans =
     1     6     8
     2     4    15
>> A-B'
ans =
     1     0    -4
    -4    -4     3
>> A*B
ans =
    21    27
    54    51
>> inv(A*B)
ans =
  -0.1318   0.0698
   0.1395  -0.0543
 

There are other operations in MATLAB apart from the standard operations. Preceding an operation with a period (.) causes the operation to be applied on an element by element basis. For example, consider the following commands:

>> C=[0 -3 4; 5 -4 3] 
C =
     0    -3     4
     5    -4     3
>> D=[1 1 9; -3 0 1] 
D =
     1     1     9
    -3     0     1
>> C*D
??? Error using ==> *
Inner matrix dimensions must agree.
>> C.*D
ans =
     0    -3    36
   -15     0     3
 

Here's another example of MATLAB's element by element procedure:

>> E=[1:4]
E =
     1     2     3     4

>> E*E                                    
??? Error using ==> *
Inner matrix dimensions must agree.
>> E^2                        %E^2 is the same as E*E
??? Error using ==> ^
Matrix must be square.

>> E.^2
ans =
     1     4     9    16

As demonstrated above, comments can be included in MATLAB with the % character. MATLAB ignores any characters after this symbol. It is good practice in any programming to include comments to explain details that are not immediately obvious.


Peter Dunn

Up Next