Lecture 001
Lecture 001
Dr A.S. Adebayo
Mechanical Engineering Department
University of Ibadan 1
Essentials of MATLAB
Programming
What Is MATLAB?
This reduces X to
X=
16 2 13
5 11 8
9 7 12
4 14 1
Arrays
Matrices are two dimensional numeric
arrays. Arithmetic operations on arrays are
done element-by-element. This means
that addition and subtraction are the same
for arrays and matrices, but that
multiplicative operations are different.
MATLAB uses a dot, or decimal point, as
part of the notation for multiplicative array
operations.
The list of operators
includes:
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose
Suppressing Output
x = a + (b-a) * rand(5)
Result
x=
19.1591 49.8454 10.1854 25.9913 17.2739
46.5335 13.1270 40.9964 20.3948 20.5521
16.0951 27.7071 42.6921 42.0027 15.8216
43.0327 14.2661 44.7478 27.2566 15.4427
31.5337 48.4759 13.3774 46.4259 44.7717
Random number generator
function X = directbinornd(N,p,m,n)
X = zeros(m,n); % Preallocate memory
for i = 1:m*n
u = rand(N,1);
X(i) = sum(u < p);
End
For example,
X = directbinornd(100,0.3,1e4,1);
For example, the following code generates
random numbers from a specific
exponential distribution using the inverse
cdf and the MATLAB uniform random
number generator rand:
mu = 1;
X = expinv(rand(1e4,1),mu);
Basic Plotting
MATLAB has extensive facilities for displaying
vectors and matrices as graphs, as well as
annotating and printing these graphs.
Now label the axes and add a title. The characters \pi
create the symbol pi.
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Result
Multiple Data Sets in One
Graph
For example, these statements plot three related
functions of x, each curve in a separate
distinguishing color.
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provides an easy way to
identify the individual plots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
Result
Specifying Line Styles
and Colors
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black')
Results
Example Colored
Surface Plots
A surface plot is similar to a mesh plot except the rectangular
faces of the surface are colored. The color of the faces is
determined by the values of Z and the colormap (a
colormap is an ordered list of colors). These statements
graph the sinc function as a surface plot, select a
colormap, and add a color bar to show the mapping of
data to color.
surf(X,Y,Z)
colormap hsv
colorbar
Result