CE 205-MATLAB for Civil Engineers
Irfan Turk
Fatih University, 2013-14
Using the Colon Operator
Colon operator is very powerful to define new matrices
or modifying an existing matrix.
>>K=1:7
returns
K= 1 2 3 4 5 6 7 . Let us define M as 3 by 5 matrix as
below.
>>M=[1 2 3 4 5; 6 7 8 9 0; 1 2 3 4 5];
>>x=M(2,:)
returns
x=
67890
Using the Colon Operator
>>x=M(2:3,:)
x=
67890
1 23 45
>>y=M(1:2,4:5)
y=
45
90
>>M(end , end)
ans=
5
returns
returns
returns
Special Matrices
Function Done Work
Example
creates an m x m matrix of zeros(size can
zeros(m) be change .i.e zeros(m,n) )
zeros(2)=[0 0;0 0]
creates an m x m matrix of ones (size can
ones(m) be change .i.e ones(m,n) )
ones(3,3)=[1 1 1;1 1 1;1 1 1]
gets the diagonal elements of a twodiag(A) dimensional matrix A
A=[1 2;4 7]; diag(A)=[1 7]
creates an m x m identity matrix (size
eye(m) can be changed. i.e. eye(n,m) )
eye(3)=[1 0 0;0 1 0;0 0 1]
Plotting
0.8
graph of sin(x)
0.6
0.4
0.2
y label
clear all;
close all;
x=0:pi/100:2*pi;
y=sin(x);
plot(x,y)
title('This is title')
xlabel('x label')
ylabel('y label')
legend('graph of sin(x)')
grid on
This is title
1
0
-0.2
-0.4
-0.6
-0.8
-1
Creates figure as on the right side in an
m file.
x label
Figure 1: Output of the commands
from the left side.
Subplots
subplot(2,1,1)
plot(x,y1,x,y2,x,y3,x,y4)
title('First Plot')
xlabel('x label')
ylabel('y label')
legend('2*cos(x)','3*cos(x)'...
,'4*cos(x)','5*cos(x)')
subplot(2,1,2)
plot(A)
title('Second Plot')
xlabel('x label 2')
ylabel('y label 2')
legend('Graph of vector A')
First Plot
y label
2*cos(x)
3*cos(x)
4*cos(x)
5*cos(x)
-5
x label
Second Plot
6
y label 2
x=0:pi/100:2*pi;
y1=2*cos(x);
y2=3*cos(x);
y3=4*cos(x);
y4=5*cos(x);
A=[0+0i 1+2i 2+5i 3+4i];
4
Graph of vector A
2
0
0.5
1.5
x label 2
2.5
Figure 2: Output of the commands
from the left side in an m file.
Subplots with Polar Plotting
x=0:pi/100:2*pi;
r=5-5*sin(x);
y=5*cos(4*x);
120
90
subplot(1,2,2)
polar(x,y)
60
150
subplot(1,2,1)
polar(x,r,'r')
10
120
30
180
330
240
270
300
60
2.5
150
210
90
30
180
210
330
240
270
300
Figure 3: Output of the commands
from the left side in an m file.
Three Dimensional Plotting
z label
x=-2:0.2:2;
y=-2:0.2:2;
[X,Y]=meshgrid(x,y);
Z=X.*exp(-X.^2-Y.^2);
surf(X,Y,Z)
title('This is a 3-D')
xlabel('x label')
ylabel('y label')
zlabel('z label')
%legend('meshgrid function')
This is a 3-D
0.5
-0.5
2
1
2
1
-1
y label
-1
-2
-2
x label
Figure 4: Output of the commands
from the left side in an m file.
Some Commands for 3-D Plots
Function
plot3(x,y,z)
comet3(x,y,z)
mesh(x,y,z)
surf(x,y,z)
contour(x,y,z)
surfc(x,y,z)
pcolor(x,y,z)
Done Work
Creates a 3-D line plot
Generates an animation version of plot3
Creates a meshed surface plot
Similar to the mesh plot
Generates a contour plot
Plots a combined surface plot and contour plot
Creates a pseudo color plot