0% found this document useful (0 votes)
13 views35 pages

MATLAB Basics: Lab 0 Introduction

This document is a lab introduction to MATLAB software for students, covering its interface, basic operations, and scripting capabilities. It includes instructions on using MATLAB as a calculator, managing variables, creating and manipulating matrices, and performing mathematical computations. The lab aims to equip students with foundational skills in MATLAB for applications in engineering and data analysis.

Uploaded by

aliyijemal28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views35 pages

MATLAB Basics: Lab 0 Introduction

This document is a lab introduction to MATLAB software for students, covering its interface, basic operations, and scripting capabilities. It includes instructions on using MATLAB as a calculator, managing variables, creating and manipulating matrices, and performing mathematical computations. The lab aims to equip students with foundational skills in MATLAB for applications in engineering and data analysis.

Uploaded by

aliyijemal28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dire Dawa University Institute of Technology

Collage of Electrical and Computer Engineering


ECEG3041 Computational Methods
Lab 0 : Introduction to MatLab

By Wendwsen Birhane
Introduction to MATLAB Software
Objective
By the end of this lab, students will be able to:
❖ Understand the MATLAB interface, toolbars, and workspace
environment.
❖ Perform simple mathematical computations and variable
operations.
❖ Create and manipulate matrices and vectors.
❖ Write and execute MATLAB scripts.
❖ Use MATLAB to plot and visualize data.
❖ The name MATLAB stands for MATrix LABoratory. MATLAB was written
originally to provide easy access to matrix software.
❖ MATLAB (Matrix Laboratory) is a high-level programming language and
environment designed for numerical computation, data analysis, and
visualization.
❖ It is widely used in Control Systems, Electrical Engineering, Signal
Processing, Robotics, and Mathematical Modeling.
MATLAB Environment Overview
When you start MATLAB, the desktop appears in its default layout.
The desktop includes these areas:
❖ Files panel — Access your files.
❖ Workspace panel — Explore data that you create or import from files.
❖ Command Window — Enter commands at the command line, indicated by the
prompt (>>).
❖ Sidebars — Access tools docked in the desktop and additional panels.
I. Use as a Calculator
You can use Matlab as a calculator by typing commands at the ≫ prompt, like
these. 1+2
5/6
cos(pi)
Note that Matlab’s standard trig functions are permanently set to radians mode,but
it also provides degree versions of the trig functions:
sind(90)
The ans command returns the last result calculated.
2*2
ans+1
To enter numbers in scientific notation, like 1.23 ∗ 1015 , use this syntax
1.23e15
Finally, note that the up-arrow key ↑ will display previous commands. And when
you back up to a previous command; you can hit Enter and it will execute again.
Or you can edit it and then execute the modified command. Do this now to re-
execute and edit some of the commands you have already typed.
II. Variables
While MATLAB has other types of variables, you will mostly just use two types:
the matrix and the string. Variables are not declared before they are used, but are
defined on the fly. The assignment command is the equal sign. For instance,
a=20
creates the variable a and assigns the value 20 to it, and then the command
a=a+1
adds one to the stored value. Note that variable names in Matlab are case sensitive,
so watch your capitalization. If you want to see the value of a variable, just type its
name like this “a”
String Variables
String variables contain a sequence of characters, like this
s='This is a string’
Some MATLAB commands require options to be passed to them using strings.
Make sure, you enclose them in single quotes, as shown above.
Matrix Variables
The “Mat” in Matlab stands for matrix, and it treats all numeric variables as
matrices. For instance, Matlab thinks the number 2 is a 1×1 matrix:
N=2
size(N)
You can enter a 1×4 row matrix using commas and braces
a=[1,2,3,4]
size(a)
or a 4×1 column matrix with semicolons and braces
b=[1;2;3;4]
size(b)
or a 3×3 matrix with columns separated by commas and rows separated by
semicolons And the matrix
A=[1,2,3;4,5,6;7,8,9]
size(A)
When you want to access the values of individual matrix elements, use the syntax
A(row,column). For example, to get the element of A in the 3rd row, 5th column
use
A(3,2)
And if you have a matrix or an array and you want to access the last element in a
row or column, you can use Matlab’s end command, like this:
b(end)
A(3,end)
The Colon (:) Command
You can build large, evenly spaced arrays using the colon (:) command. To build
an array x of values starting at x = 0, ending at x = 10, and having a step size of dx
= 0.5 type this:
x=0:.5:10
And if you leave the middle number out of this colon construction, like this
t=0:20
then Matlab assumes a step size of 1.
Selecting Rows and Columns
Sometimes you will want to select part of a matrix and load it into another array.
This is also done with Matlab’s all-purpose colon (:) command. To select just part of
row or column, use commands like this:
c=A(2,1:2)
The variable c now contains the first two elements of the second row of A. To load a
column vector b with all of the entries of the third column of the matrix A, you can
use the syntax
b=A(1:end,3)
Recall that the first index of a matrix is the row index, so this command tells Matlab
to select all of the rows of A in column 3. Since this type of operation is so common
in Matlab, there is a shorthand for selecting all of the entries in a given dimension:
just leave off the numbers around the colon, like this
b=A(:,3)
c=A(2,:) And to load a row vector c with the contents of the second row of the matrix A use
Add and Subtract
Matlab knows how to add and subtract arrays and matrices. As long as A and B are
two variables of the same size (e.g., both 2×3 matrices), then A+B and A-B will
add and subtract them as matrices:
A=[1,2,3;4,5,6;7,8,9]
B=[3,2,1;6,4,5;8,7,9]
A+B
A-B
Multiplication and Division
A*B
A*[1;2;3]
A^3
But there are lots of times when we don’t want to do matrix multiplication.
Sometimes we want to take two big arrays of numbers and multiply their
corresponding elements together, producing another big array of numbers. Because
we do this so often (you will see many examples later on) Matlab has a special
symbol for this kind of multiplication:
.*
For instance, the dot multiplication between the arrays [a,b,c] and [d,e,f] would be
the array [a*d,b*e,c*f]. And since we might also want to divide two big arrays this
way, Matlab also allows the operation
./
If we want to raise each element of an array to a power, we use
.^
For example, try
I. [1,2,3].*[3,2,1] II. [1,2,3]./[3,2,1] III. [1,2,3].^2
Sum the Elements
The command sum adds up the elements of the array. For instance, the following
commands calculate the sum of the squares of the reciprocals of the integers from
1 to 10,000.
n=1:10000;
sum(1./n.^2)
For matrices the sum command produces a row vector which is made up of the
sum of the columns of the matrix.
A=[1,2,3;4,5,6;7,8,9]
sum(A)
If you want to add up all of the elements in the array, just nest the sum command
like this
sum(sum(A))
Function Meaning
cos(x) Cosine of x (radians)
sin(x) Sine of x (radians)
tan(x) Tangent of x (radians)
acos(x) Inverse cosine of x (returns radians)
asin(x) Inverse sine of x (returns radians)
atan(x) Inverse tangent of x (returns radians)
Four-quadrant inverse tangent (angle between x-axis and
atan2(y,x)
point (x,y), in radians)
Function Meaning

cosd(x) Cosine of x (degrees)

sind(x) Sine of x (degrees)

tand(x) Tangent of x (degrees)

acosd(x) Inverse cosine of x (returns degrees)

asind(x) Inverse sine of x (returns degrees)

atand(x) Inverse tangent of x (returns degrees)

atan2d(y,x) Four-quadrant inverse tangent in degrees


Function Meaning

exp(x) Exponential function ( e^x )

log(x) Natural logarithm (base e)

log10(x) Base-10 logarithm

log2(x) Base-2 logarithm

sqrt(x) Square root of x


Function Meaning / Description
clc Clears the Command Window (useful for neat output).
clear Removes all variables from the workspace.
clear x y Clears specific variables x and y.
close all Closes all open figure windows.
close 3 Closes figure number 3.
length(a) Returns the number of elements in vector a.
size(C) Returns the dimensions (rows and columns) of matrix C.
ceil(x) Rounds x upward to the nearest integer.
fix(x) the nearest integer to x looking toward zero
floor(x) Rounds x downward to the nearest integer.
round(x) Rounds x to the nearest integer.
sign(x) Returns 1 if x>0, −1 if x<0, and 0 if x=0.
abs(x) Returns the absolute value of x.
sqrt(x) Square root of x.
mod(a,b) Remainder after division of a by b.
rem(a,b) Remainder using truncated division.
sum(A) Sum of elements of A.
prod(A) Product of elements of A.
mean(A) Mean (average) value of A.
median(A) Median value of A.
max(A) Maximum element in A.
min(A) Minimum element in A.
sort(A) Sorts elements of A in ascending order.
rand(n,m) Creates an n×m matrix of random numbers between 0 and 1.
randn(n,m) Creates an n×m matrix of normally distributed random numbers.
zeros(n,m) Creates an n×m matrix filled with zeros.
ones(n,m) Creates an n×m matrix filled with ones.
eye(n) Creates an n×n identity matrix.
diag(A) Returns the diagonal elements of A.
det(A) Determinant of matrix A.
inv(A) Inverse of matrix A.
rank(A) Rank of matrix A.
trace(A) Sum of diagonal elements of A.
reshape(A,m,n) Reshapes matrix A into m×n dimensions.
transpose(A) or A' Transpose of matrix A.
disp(x) Displays value of x without variable name.
fprintf() Prints formatted text or numbers.
input('text') Prompts the user for input.
help functionname Displays help for a specific function.
who Lists variables currently in the workspace.
whos Lists variables with details (size, type, bytes).
Scripts
Example Output (if
Command Format Explanation Meaning / Description
run)
Displays a message and Enter a value for N
N = input(' Enter a Prompts user for input; ' ' encloses
waits for user to enter a - 10(then stores N
value for N - ') prompt text
value for N = 10)
%g → Compact format (auto
fprintf(' N =%g Prints a number in shortest
chooses fixed or exponential)\n → N =500
\n',500) readable form
New line
fprintf(' x =%1.12g %1.12g → Up to 12 significant Prints π with 12 significant
x =3.14159265359
\n',pi) digits figures
%e → Exponential x
fprintf(' x =%1.10e Prints π in scientific
notation%1.10e → 10 digits after =3.1415926536e+
\n',pi) notation
decimal 00
%f → Fixed-point decimal%6.2f
fprintf(' x =%6.2f Prints π rounded to 2
→ 6 total width, 2 digits after x = 3.14
\n',pi) decimal places
decimal
fprintf(' x =%12.8f y %12.8f → 12 total width, 8 Prints two numbers neatly x = 5.00000000 y
=%12.8f \n',5,exp(5)) decimals (for each variable) aligned: x=5, y=exp(5) =148.41315910
Add Comments
Document your scripts by including comment lines that begin with %, like this:
% This is a comment line
Or you can put comments at the end of a line of code like this:
f=1-exp(-g*t) % compute the decay fraction
Wrap Long Lines
Make your code more readable by continuing long program lines onto successive
lines by using the ... syntax, like this
a=sin(x)*exp(-y) + sqrt(b^2-4*a*c)/2/a + c1*d3 +...
log(z) + sqrt(b);
clear; % clear all variables from memory
close all; % close any figure windows
% N is the largest number to test
N=12;
% steps the value of n from 1 to N
for n=1:N
% calculate the integer remainder of this value of n divided by 3
r = mod(n,3);
if (r==0)
% indicate that 3 is a factor of this n
fprintf(' 3 is a factor of %g \n', n);
else
% indicate that if 3 is not a factor of this n
fprintf(' 3 is not a factor of %g \n', n);
end
end
Loops and Logic
for Loops
A loop is a way of repeatedly executing a section of code. A for loop looks like this:
for n=1:N
% Put code here
end
which tells Matlab to start n with a value of 1, then increment the value by 1 over and over until
it counts up to N, executing the code between for and end for each new value of n. Here are a
few examples of how the for loop can be used.
Summing a series with a for loop
Let’s do the sum

with N chosen to be a large number.


clear; close all;
% set s to zero so that 1/n^2 can be repeatedly added to it
s=0;
N=10000; % set the upper limit of the sum
for n=1:N % start of the loop
s = s + 1/n^2; % add 1/n^2 to s each iteration
end % end of the loop
fprintf(' Sum = %g \n',s) % print the answer
Let’s calculate N! = 1 ·2 ·3···(N -1) · N using a for loop that starts at n = 1 and
ends at n = N , doing the proper multiply at each step of the way.
clear; close all;
P=1; % set the first term in the product
N=20; % set the upper limit of the product
for n=2:N % start the loop at n=2 because we already loaded n=1
P=P*n; % multiply by n each time, put the answer back into P
end % end of the loop
fprintf(' N! = %g \n',P) % print the answer
Logic
Often we only want to do something when some condition is satisfied, so we need
logic commands. The simplest logic command is the if statement, which works like
this: clear; close all;
a=1;
b=3;
if a>0
c=1 % If a is positive set c to 1
else
c=0 %if a is 0 or negative, set c to zero
end
% if either a or b is non-negative, add them to obtain c;
% otherwise multiply a and b to obtain c
if a>=0 | b>=0 % either non-negative
c=a+b
else
c=a*b % otherwise multiply them to obtain c
end
while loops
There is also a useful logic command that controls loops: while. Suppose you don’t
know how many times you are going to have to loop to get a job done, but instead
want to quit looping when some condition is met. For instance, suppose you want to
add the reciprocals of squared integers until the term you just added is less than
1e-10. Then you would change the loop in the σ 1 /𝑛2example to look like this
clear; close all;
term=1 % load the first term in the sum, 1/1^2=1
s=term; % load s with this first term
% start of the loop - set a counter n to one
n=1;
while term > 1e-10 % loop until term drops below 1e-10
n=n+1; % add 1 to n so that it will count: 2,3,4,5,...
term=1/n^2; % calculate the next term to add
s=s+term; % add 1/n^2 to s until the condition is met
end % end of the loop
fprintf(' Sum = %g \n',s)
Basic Plotting
One of the nicest features in Matlab is its wealth of visualization tools.
Linear Plots
Making a Grid
Simple plots of y vs. x are done with Matlab’s plot command and arrays. To build
an array x of x-values starting at x = 0, ending at x = 10, and having a step size of
.01 type this:
x=0:0.01:10;
To make a corresponding array of y values according to the function y(x) = sin(5x)
simply type this
y=sin(5*x);
Plotting the Function
Once you have two arrays of the same size, you plot y vs. x like this
plot(x,y);
Controlling the Axes
Matlab chooses the axes to fit the functions that you are plotting. You can override
this choice by specifying your own axes, like this:
axis([0 10 -1.3 1.3])
Or, if you want to specify just the x-range or the y-range, you can use xlim:
plot(x,y)
xlim([0 10])
or ylim:
plot(x,y)
ylim([-1.3 1.3])
And if you want equally scaled axes, so that plots of circles are perfectly round
instead of elliptical, use
axis equal
Plot Appearance
Line Color and Style
plot(x,y,'r-')
plot(x,y,'g.')
help plot
xlabel('Distance (m)')
ylabel('Amplitude (mm)')
title('Oscillations on a String')

You might also like