Unit# 9- MATLAB 2
Course Outline Return to Unit
MATLAB:Hints
As you read this material we strongly recommend that you activate your MATLAB window and try the commands explained right there and then.

Constructing arrays

A = [1,2,3 ; 0,1,5]

 

1

2

3

0

1

5

B = [1 : 0.1 : 1.5]

 

1, 1.1, 1.2, 1.3, 1.4, 1.5

C = [ a( : , 1 ), a( : , 3) ]

 

1

3

0

5

Array operations

Definitions of arrays

X = [1,2,3]

Y = [5,6,7]

Z = [2,1 ; 3,4]

W = [7 ,1 ; 3, 1]

Scalar product

3 * X =

3, 6, 9

 

 

Addition / subtraction

X + Y =

6, 8, 10

 

Term by term power

X .^ 2 =

1, 4, 9

Term by term product

X .* Y =

5, 12, 21

Matrix multiplication

   Z    *   W   =    R

m X n   n X k   m X k

2*7+1*3

2*1+1*1

3*7+4*3

3*1+4*1

Input / Output

Reading from a file 

load scores.txt

Prompting input:

a = input ( ‘ ------------‘);

Writing to a file:

FileID = fopen ( ‘ report.txt’, ‘wt’);

fprintf ( FileID, ‘ --------- %10.3 f ------------‘ , a );

fclose ( FileID );

Printing to the screen a table of cosines ( angles in degrees)  :

B=[ 0, 30, 45, 60, 90 ;  1 , 0.866 , 0.707 , 0.5 , 0 ];

fprintf(' degrees     cos  ')

fprintf('\n  %5.0f   %5.3f ', B);

Plots

Basic plotting:

plot( xdata, ydata, ‘ r + -‘ );   %  will plot in red line and with + marks

title ( ‘ parabola   ‘);

xlabel ( ‘  my indepentent variable  ‘);

Multiple plots

 

hold on;

Subplots with m windows in the vertical and n windows in the horizontal

subplot( m, n, k);   % where k is given by:

1

2

3

4

Branching

if ( condition )

block ………

elseif ( condition )

block ……….

else

block ………….

end

Operators:

 

<

<=

>

>=

= =

~ =

&

|

 

Note the differences from C++ in the last three operators

Loops

while ( condition )

block

end

for   k = 3 : 0.75 : 6

block

 end

User defined functions

File polar.m 

(match names of file and function )

 

function [ r, theta] = polar ( x , y)

% calculates the polar coordinates

r = sqrt( x ^ 2 + y ^ 2 );

theta = atan ( y / x );

File ex1.m

 

X = 2.34;

Y = 5.78;

[ r , theta ] = polar ( x , y );

fprintf(‘ r = %f ,  theta = %f ’, r, theta);

Solving systems of equations:

Given the system   A x = b

 

x = A \  b ;

For square matrix A:

det ( A );         % calculates the determinant

inv ( A);          % calculates the inverse

Jacob Y. Kazakia © 2001 All rights reserved