Introduction to Computational Science (1999)
CZ1103, Solution to Lab. I (Matlab)

Part A

Evaluate the following expressions using Matlab

>>1+1/2+1/3+1/4+1/5+1/6+1/7+1/8+1/9+1/10+...

1/11+1/12+1/13+1/14+1/15+1/16+1/17+1/18+1/19+1/20

Ans = 3.5977

Alternatively, you can use

>>x=1:20;
>>sum(1./x)

>>exp(cos(pi/4)+i*sin(pi/4))

ans =

1.5419 + 1.3175i

To solve the equations, we can use

>>A=[1,0,-8;1,2,1;0,9,19];

>>b=[5;10;1];

>>u=A\b

u=

13

-2

1

To verify that the solution is correct, we evaluate

>>A*u

ans =

5

10

1

These are the numbers on the right hand side the equations; so the solution is correct

Part B

Create a 5 by 5 magic square A using magic(5).

>>A=magic(5);

» sum(A(1,:)) %sum of first row

ans =

65

» sum(A(2,:)) %sum of second row

ans =

65

» sum(A(3,:)) %sum of third row

ans =

65

» sum(A(4,:)) %sum of fourth row

ans =

65

» sum(A(5,:)) %sum of fifth row

ans =

65

» sum(A(:,1)) %sum of first column

ans =

65

» sum(A(:,2)) %sum of second column

ans =

65

» sum(A(:,3)) %sum of third column

ans =

65

» sum(A(:,4)) %sum of fourth column

ans =

65

» sum(A(:,5)) %sum of fifth column

ans =

65

Alternatively, we may use sum(A) and sum(A') to find out the sums over all columns and all rows.

» A/A

ans =

1.0000         0             0             0             0

0                 1.0000     0.0000      0.0000     -0.0000

0.0000         -0.0000     1.0000 -    0.0000     -0.0000

0                 0                0             1.0000     0

0                 0                 0             0             1.0000

» A./A

ans =

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

A/A is AA-1 which is equal to identity matrix; while A./A is element-by-element division, so the result is the matrix whose elements are all 1.

» A^2

ans =

1090 900 725 690 820

850 1075 815 720 765

700 840 1145 840 700

765 720 815 1075 850

820 690 725 900 1090

» A*A

ans =

1090 900 725 690 820

850 1075 815 720 765

700 840 1145 840 700

765 720 815 1075 850

820 690 725 900 1090

» A.^2

ans =

289 576 1 64 225

529 25 49 196 256

16 36 169 400 484

100 144 361 441 9

121 324 625 4 81

» A.*A

ans =

289 576 1 64 225

529 25 49 196 256

16 36 169 400 484

100 144 361 441 9

121 324 625 4 81

A^2 and A*A give riese to matrix multiplication between A and A; A.*A and A.^2 indicate element-by-element multiplication (each element squared)

» A+2

ans =

19 26 3 10 17

25 7 9 16 18

6 8 15 22 24

12 14 21 23 5

13 20 27 4 11

A+2 means that add 2 to each element of A.

Part C

Use Matlab to plot a sequence of data points labeled by '+' connected by line segments. The x and y coordinates of the data points are given by

.

Ans.:

» x=10:10:400;

» y=200*exp(-0.002*x).*sin(0.05*x)+250;

» plot(x,y,'-+')

Part D (optional)

» theta=0:0.01:2*pi;
» x=10*cos(theta);
» y=10*sin(theta);
» plot(x,y)
» axis equal