You are on page 1of 110

tutorial 45.

com
Matlab Tutorial
A.The basics
Write a function that find the volume of a 3D rectangle in Matlab
Scalar functions in Matlab: e Matlab, Cosine function and more
Left division vs Right Matrix division – Matlab
Convert numbers from Polar to Cartesian and vice versa

B. Plotting
Plotting in Matlab – The Basics
Graph the equation by plotting points
Plotting equations using EZPLOT – Matlab
EZPLOT vs PLOT in Matlab
Conditional plotting in Matlab
Matlab plot colors and Styles

C.Equations
Matlab solves system of equations
Solving polynomial equations using Matlab
Derivative in Matlab
Matlab Polynomial: Division and Multiplication
Solve equations with unknown coefficients with Matlab

D.Programming
For loop in Matlab

E. Matrices
Matlab Matrix Operations
Write a Matlab function that rotate a Matrix by 90 degrees
Matrix multiplication – Matlab
Matlab tricks: Creating an “array”, modifying matrix elements
Sort a matrix in Matlab
Vectors in Matlab: Basic Operations
F. Numerical method
Newton Raphson method Matlab
Euler method Matlab code

G. Exercises
Matlab Exercises
Matlab Matrix Operations – Exercise
A. Write a Function That Find the Volume of a
3D Rectangle in Matlab
Tutorial45 MathLab

There is a function behind every Matlab code that performs a computational task,
and here is how you can create your own function that will help you go faster
while working with Matlab.

We will be creating a simple one line code function in this post, just to help you
have a glimpse into how creating functions in Matlab

Write a function in Matlab


Here is what you do when writing your own function in Matlab.

Open a new function file


Here is what appear on the next window
In Matlab, the section after the % is considered as comment (the section that
appears in green in the window above)

Here is how we need to structure our Matlab function

1
function [v] = vol(L,W,H)

2 % L is the length of the 3D rectangle

3 % W is the width of the 3D rectangle

4 % H is the height of the 3D rectangle

v= L*W*H;
5
end
6

You need to copy the whole code above and paste it in the file, Save the file with
the name vol.m and make sure not to change the directory Matlab will guide you
to.

Here is how it will look


How to use the Matlab function we have just created
Every time you will need to compute the such a volume, simply type the following
code

vol(L,W,H)

where L, W, And H will be real numbers.

Example
Let’s say, we need the volume of a 3D rectangle with L, W and H being
respectively 10, 3, 15, we can simply type:

vol(10,3,15)

And Matlab will call the function vol, compute the volume of the 3D rectangle and
display the following.
If you are working in an exercise where you will often need this volume, you can
just use this function instead of actually computing manually the volume each
time you need it. It might not look very important in this exercise, but when you
have a complex operation you need to perform often in Matlab, creating a
function doing it automatically will be time efficient and necessary.

Using this technique, you can create more complex functions in Matlab and have
an easier life while using them. Learn more about functions in Matlab.
A. Scalar Functions in Matlab: E Matlab,
Cosine Function and More
Tutorial45 MathLab

These are few Basic tools you will need to know if you are just starting learning
Matlab.

Scalar functions in Matlab


Before fully diving into trigonometric functions, it is necessary to state that Matlab
takes as input radians while working with trigonometric function meaning and
uses the symbol pi for π

Trigonometric sine

Matlab code

sin(pi)

Trigonometric cosine

Matlab code

cos(pi)

Trigonometric tangent
Matlab code

tan(3*pi/2)

Trigonometric inverse sine (arcsine)

Matlab code

asin(1)

Trigonometric inverse cosine (arccos)

Matlab code

acos(0.5)

Trigonometric inverse tangent (arctan)

Matlab code

atan(3/2)

e Matlab (exponential)

Matlab code

exp(x)

Natural logarithm
Matlab code

log(5/2)

Absolute value

Matlab code

abs(a*x+b)

Square root

Matlab code

sqrt(a*b)

Remainder after division


This function help you find the remainder after a division. We will use as an
example the remainder of the division of 5 by 2, which is one.

Matlab code

rem(5,2)

which returns

Round towards nearest integer


This function will allow you to round values towards the nearest integer if you are
not interested in working with decimal numbers. It is most useful while you want
to round the result of an operation.

Matlab code

round(2.9)

Which returns

Round towards negative infinity


floor(x) rounds the elements of x to the nearest integers towards minus infinity.

Round towards positive infinity


As opposed to the floor function, ceil(x) rounds the elements of x to the nearest
integers towards infinity.

Content you might like:


Write a function that find the volume of a 3D rectangle in Matlab
Scalar functions in Matlab: e Matlab, Cosine function and more
Left division vs Right Matrix division – Matlab
Convert numbers from Polar to Cartesian and vice versa
F. Euler Method Matlab Code
Tutorial45 MathLab

The Euler method is a numerical method that allows solving differential equations
(ordinary differential equations). It is an easy method to use when you have a
hard time solving a differential equation and are interested in approximating the
behavior of the equation in a certain range.

Here we will see how you can use the Euler method to solve differential
equations in Matlab, and look more at the most important shortcomings of the
method.

It is to be noted that you can only make use of this method when you have the
value of the initial condition of the differential equation you are trying to solve.

Euler method
Let’s start with a little of theory which you can learn more about on Wikipedia if
you wish.

Here are some methods added to the Forward Euler method that falls into the
same category while using numerical methods of such: The forward difference,
the backward difference and the central difference method.

Forward difference

Backward difference

Central difference
Euler Method Matlab
Forward difference example
Let’s consider the following equation

The solution of this differential equation is the following

What we are trying to do here, is to use the Euler method to solve the equation
and plot it along side with the exact result, to be able to judge the accuracy of the
numerical method.

To solve this equation using the Euler method we will do the following

If we rewrite the forward Euler formula above with a different look

Replacing this expression in the equation we are trying to solve will give the
following

If we consider that
And rewrite the equation accordingly, we obtain

Feel free to further simplify the expression above, but at this point, we are ready
to start coding in Matlab.

The Matlab code


h=0.1; % step's size

N=10; % number of steps

y(1)=1;

for n=1:N

y(n+1)= y(n)+h*(-6*y(n));

x(n+1)=n*h;

end

plot(x,y)

The graph
Let’s reduce the step’s size and see how it affects accuracy

The Matlab code


h=0.01; % step's size

N=100; % number of steps

y(1)=1;

for n=1:N

y(n+1)= y(n)+h*(-6*y(n));

x(n+1)=n*h;

end

plot(x,y,'r')

The graph
This is telling us that when we reduce the value h, it reduces the error. Can we
now try comparing our best graph to the exact graph?

Here is the code to help plot the exact graph

The Matlab code


x=0:0.001:1;

y=exp(-6.*x);

plot(x,y,'g')

The graph
We can notice by looking at the graph above how both graphs are close to being
identical.

For simple functions like the one we just tested, using this Euler method can
appear to be accurate especially when you reduce h, but when it comes to
complex systems, this may not be the best numerical method to use to
approximate the plot of ODEs. Improved methods exist just like the famous
Runge-Kutta method
C. Can Matlab solve a system of equations?
Yes, Matlab can help you easily solve a system of equations. Let’s jump into
some examples and show you how you go about it.

Using Matlab to Solve a system of equation with two


unknowns
Let’s consider the following system of equations

The above equation can be written in the matrix form


The equation can be rewritten as

Now we are set to use Matlab!

A=[2 3;1 1];

B=[8;3];

X=inv(A)*B

The last line does not have; at the end.

You will see an answer like this

Which simply means that

Let’s elaborate a little more in details here before moving forward. What we have
done above is the following.
We have written the equation in the form

Where

So to have at the end the equation on the form

Example 2: System of equation with three unknowns


let’s consider the following system of equations

Using the same technique we used above we can write the system in the
following form
Giving commands to Matlab will look like the following

A=[1 3 -2;3 2 -1;2 -1 -3];

B=[1;2;13];

X=inv(A)*B

To end up with the following result

Final thought
If you are working on a system of equations where the number of unknowns is
equal to the number of equations, this method is a good way to go. This
restriction is due to the fact that using the system of matrices to solve such
system of equations requires that the matrix A is invertible. If there are no
possibilities of finding the inv(A) then this method is totally useless.

Posts you might like:


Write a function that finds the volume of a 3D rectangle in Matlab
Scalar functions in Matlab: e Matlab, Cosine function and more
Left division vs Right Matrix division – Matlab
Convert numbers from Polar to Cartesian and vice versa
C. Solve Equations With Unknown
Coefficients With Matlab
Tutorial45 MathLab

We have so far been working with numbers, totally ignoring one of the most
rewarding ability Matlab put to our use: the possibility to work with symbolic
expressions.

In many college algebraic courses, it is taught how to use and simplify equations
with symbolic expressions, where one of the major task is to be learn how to
express one symbol with respect to others. Here we will attempt to use Matlab to
solve some problems we lately worked on using real numbers.

Example 1
Let’s consider the following equation

We all know that this is second order polynomial equation and we know how to
solve it. Let’s try using Matlab to solve this very equation as it is, assuming we
don’t know what the value of the coefficients are.

The code

syms a b c x

f = a*x^2 + b*x + c

solve(f)

Which returns
Let’s ask Matlab to give us less difficulties reading the answer

The code

pretty(ans)

Which returns

Which we all remember from basic algebra.

If you would like to solve the equation with respect to a, you can state it like this

solve(f,a)

Which returns
Example 2
Let’s now use the following equation

Just like the second order polynomial equation in example 1, this will be like it

The code

syms a b c d x;

f = a*x^3 + b*x^2 + c*x + d;

l = solve(f);

pretty(l)

Which returns
Example 3
This is also a nice method you can make use of, to help you remember a
formula. Let’s consider the following Matrix

Let’s find the determinant of A

The code
syms A11 A12 A13 A21 A22 A23 A31 A32 A33

A=[A11 A12 A13 ; A21 A22 A23 ; A31 A32 A33]

l = det(A)

Which returns

Example 4
Let’s do some Matrix operation with the following matrices: Addition and
Multiplication.

the code

syms B11 B12 B21 B22 C11 C12 C21 C22;

B = [B11 B12 ; B21 B22];

C = [C11 C12 ; C21 C22];

Add = B + C;

Mul = B*C;

Add

Mul

Which returns
Example 5
Let’s end this session with solving the following equation.

The code

syms a b x

g = a^x + b;

l = solve(g);

pretty(l)

Which returns
F. Newton Raphson Method Matlab
Tutorial45 MathLab

The aim of this session is to use a basic example to illustrate how to use the
Newton Raphson method in Matlab.

We will make use of the ode45 solver, and use boundary conditions in the
following example.

Here come the exercise

With boundary conditions

Here is the route we will take

Newton Raphson method in Matlab


The code below solve this initial value problem (IVP) using the function ode45

it used the Newton Raphson method in the iteration process to approach the
exact solution and finally end the iteration when y(1) is accurately converged up
to the third decimal.

In the beginning of the problem we divide the ODE (ordinary differential equation)
to a set of first order equations and we use 1 as initial guess for y'(0)

Here is the code


ua=0;
1
s(1)=1; %First guess for the derivative
2
s(2)=1.1; %second guess for the derivative

4
tb=1; %Second time

5 target_ub=0; % target

7 f=@(t,y) [y(2); 1./(1+y(1))^2]; % set of 1st order ODE

8 rb=@(v) (v-target_ub) % boundary conditions at b

[t,y]=ode45(f,[0 tb],[ua; s(1)]);


10
ub(1)=y(end,1);
11

12
for (j=2:50) % stop after 50 iteration even if the accuracy is not
13 reached

[t,y]=ode45(f,[0 tb],[ua; s(j)]);


14
ub(j)=y(end,1);
15
if abs(rb(ub(j)))<0.001 % quit the for loop if accuracy reached
16
break
17
end
18
s(j+1)=s(j)-rb(ub(j))*(s(j)-s(j-1))/(rb(ub(j))-rb(ub(j-1)));
19 end

20

plot(t,y(:,1)) % plot the last solution


21
xlabel('t')
22
ylabel('y')
23
grid on
24

25

26

The Plot
A. Left Division vs Right Matrix Division –
Matlab
Tutorial45 MathLab

There are two operators allowing to divide in Matlab:

 The right division represented by the symbol / (slash)


 The left division represented by the symbol \ (Backslash)

These two operators differ from each other

Using numbers, the right division will be the conventional division we all day
make use of, so

Contrary to the right division, the left division reverse the division, meaning

Matrix division in Matlab


The right Matrix divide
Let’s consider two Matrices A and B

Using the right division

Matlab code

1 A=[1 2 ; 2 2];
2 B=[3 2 ; 1 1];

A/B % You can also use A*inv(B)


3

which returns

rewritten, it will look like this

The left Matrix divide


The right matrix divide is roughly the same as

Which leads to a complete different result from the preceding operator.

This technique can be used to quickly compute the solution of the equation

So, using our early defined matrices

will be written
1 A=[1 2 ; 2 2];

2 B=[3 2 ; 1 1];

A\B % You can also use inv(A)*B


3

which returns

Which rewritten will look like

The Matrix division, element by element


We thought it will be also necessary you have a grip on the element-by-element
Matrix division in Matlab

To divide Matrices, element-by-element, the following formula is useful

Where
The code

1 A./B

Content you might like:


 Matlab Matrix Operations
 Write a Matlab function that rotate a Matrix by 90 degrees
 Matrix multiplication – Matlab
 Matlab tricks: Creating an “array”, modifying matrix elements
 Sort a matrix in Matlab
 Vectors in Matlab: Basic Operations
 D. For Loop in Matlab
 Tutorial45 MathLab
 Working and constructing for loops in Matlab happen the exact same way
they do in other programming languages, at the only difference that in
Matlab the first index the for loop goes through is never zero. In Matlab,
the first index is 1, and this is an information you should always remember
while working with for loops in Matlab.
 We have recently used a for loop here, while going through Euler methods
in Matlab without spending a lot of time on the for loop itself, in this post we
will work with the later a little intensively.
 For Loop in Matlab
 let’s start with the basic design flow of a for loop structure.


 Image credit: programiz.com
 The image above shows you how the loop is set to work. Without spending
too much energy in understanding how this work with only the theoretical
explanation, let’s test it on some real world examples.
 For loop Matlab Example
 Example 1
 Sum all elements of a vector
 In the first example, we just want to sum all elements of a vector
 if the vector is the following


 We want to find


 We want to sum elements in an iterative way. We will create a variable m
and at each iteration, we will update its value till reaching the last value of
the vector.
 The code looks like

1
sum=0;

2 A=[7 14 4 3 12 5 0 1];

3 for i=1:length(A)

4 sum=sum+A(i);

end;
5
sum
6

 Example 2
 In this example, we will simply find the factorial of a number which we will
request from the user.
 More explicitly, we want the mini program to ask a number from a user,
verify that the number is not negative, and compute its factorial.
 The code
1
numb=input('Enter a number: ');
2
fact=1;

3
if numb<0

4 fprintf('the number you have entered is negative');

5 else

6 for i=1:numb

fact=fact*i;
7
end
8
fact
9
end
10

 Example 3
 This one is more an exercise than an example. Write a Matlab function that
computes the following sum while requesting the value of x and n from the
user.


 To call the function, the user should use the following


 Feel free to drop your code in the comment section.
C. Solving Polynomial Equations Using Matlab
Tutorial45 MathLab

Polynomial equations are some of the most popular types of equations in Math.
Knowing how to solve them is a thing but actually solving them is another thing.

The methods you can use to solve them are many, but if you happen to have
Matlab or the free Matlab alternative Octave you might as well be good using
them to buy time if the purpose of solving the equation is more than simply
solving the equation.

Caution: The following methods will help you solve polynomial equations quickly
but will not show you how to manually solve polynomial equations, it will simply
help you get results faster. This can be helpful if you are not interested on the
method but on the answers and may also be very useful to check your result
after manually solving your equations.

Solving polynomial equations using Matlab


Solving quadratic equations using Matlab
Quadratic equation are equations in the form

Where

So you will also find quadratic equations in the form

or
Let’s go ahead and solve the following equation with Matlab

To solve this equation with Matlab you will enter the following code

roots([1 -3 2])

and Matlab will give you the roots of the polynomial equation

If the equation was the following

the code would be

roots([1 0 -4])

and the result

Solving cubic equations using Matlab


Let’s use the following equation
The line of code to solve it won’t be that different compared to the previous one.
The only difference here is that we have non-zero third order coefficient to add to
it

roots([1 6 0 -20])

Do not forget to add 0 between 6 and -20 since the first-order coefficient is zero

The result will be

Solving quartic equations using Matlab


Using the following polynomial equation

The code will be

roots([1 2 -6*sqrt(10) +1])

And the result will be

The higher-order the higher number of coefficients. Remember the order which
with you enter coefficients in the code affect the result, and always remember to
put 0 to indicate where the coefficient is not existent for lower exponents of the
equation
E. Matlab Matrix Operations
Tutorial45 MathLab

If you ever tried to work with huge matrices, you will know how unpleasant and
tedious. Here is where Matlab come to play, it makes working with Matrices
easier.

With Matlab, one of the major problem for beginners is to understand how the
software works and what the software need in order to help them accomplish
their goal using it.

In this read, we will hand over to you some basic Matlab Matrix operation and
how to use them to get what you want.

Content:

Write a Matrix in Matlab


Find the size of a Matrix
Add Matrices
Divide Matrices element by element
Find the inverse of a Matrix
Find the determinant of a Matrix
Define a Matrix with Random elements
Find the diagonal of a Matrix
Compute the Transpose of a Matrix
Extract an element in a Matrix
Multiply Matrices
Multiply 2 Matrices element by element
Create a Matrix with all elements equal to zero
Create a Matrix with All elements equal to one

Matlab Matrix Operations


Write a Matrix in Matlab

we will write
A=[1 1 -2;2 2 1;2 1 1]

after pressing ENTER, here is how it will look in Matlab window

Find the size of a Matrix


The size of a Matrix is its number of rows and columns. To find the size of a
Matrix, use the following code

size(A)

Note A here is the matrix we created in the previous step.

Here is its size

Meaning, A has 3 rows and 3 columns.

Let’s try a second example.

If we type

size(B)

We will see the following


Add Matrices
To add two matrices A and B, we need size(A) to be identical to size(B)

So, let’s create a new Matrix C with the same size as A

Now we can add A and C using the following code

A+C

Divide Matrices element by element


To divide two Matrices element by element use the following

A./C

Remember both matrices need to have the same size.


Find the inverse of a Matrix

To find the inverse of a Matrix, use the code:

inv(A)

Find the determinant of a Matrix


To find the determinant of a Matrix in Matlab, use the following code

det(A)
Define a Matrix with Random elements
To create a Matrix with Random element in Matlab, use

rand(3,2)

Where (3,2) is the size of the Matrix

Find the diagonal of a Matrix


DIAG help access diagonals of Matrices in Matlab.

To find the main diagonal of A, we will use

diag(A)

to find the first upper diagonal use

diag(A,1)

to find the first lower diagonal use

diag(A,-1)

Here is how Matlab read matrix diagonals


Compute the Transpose of a Matrix
To find the transpose of a Matrix, use the following

A'

or

transpose(A)

Here is the transpose of A

Extract an element in a Matrix


You can individually access element of a Matrix or a whole vector.

Let’s consider the following Matrix

If I need to access the first row of the Matrix, I will use the following code

C(1,:)

I will use the following to access the element on the first rows-second column.

C(1,2)

The following will help access element of the third column

C(:,3)
Multiply Matrices
To multiply A X B, A and B being two distinct matrices, A and B has to obey
these conditions.

To multiply A by B in Matlab, use the code

A*B

Multiply 2 Matrices element by element


To multiply a Matrices element by element, remember the size of the two
matrices has to be the same.

Use the following line

A.*B

Create a Matrix with all elements equal to zero

To create a Matrix with all elements equal to zero, use the following code

G=zeros(3,4)

where (3,4) is the size of the Matrix

Create a Matrix with All elements equal to one

To create a Matrix with all elements equal to one, use the following code
O=ones(4,5)

where (4,5) is the size of the Matrix

Summary of Matrix functions


size: Size of a matrix
det: Determinant of a square matrix
inv: Inverse of a matrix
rank: Rank of a matrix
rref: Reduced row echelon form
eig: Eigenvalues
poly: Characteristic polynomial
norm: Norm of matrix
lu: LU factorization
svd: Singular value decomposition
eye: Identity matrix
zeros: Matrix of zeros
ones: Matrix of ones
diag: extract/create diagonal of a matrix
rand: randomly generated matrix
B. Ezplot vs plot in Matlab
Plotting with EZPLOT
EZPLOT is an easy to use function plotter. Compared to PLOT, it is a hassle-
free-plotter. All you need to do to use it is to state the function you would like to
plot, and it does the rest of the job.

Let’s use the examples below to see how to plot using with EZPLOT in Matlab.

Example 1
Here is a function which we want to graph.

The code

1 y=ezplot('(2*x+1)/(x-3)')

2 set(y,'Color','b','LineWidth',2) % Make the line blue and the linewidth 2

The Graph
Example 2

The code

1 f=ezplot('sin(x*y)')

2 set(f,'Color','r') % Make the line red

The graph
Plotting with PLOT
Example 1

The code

x=-10:0.5:10; % x varies from -10 to 10 with an incremental step of 0.5


1
y=(2.*x+1)./(x-3);
2
plot(x,y,'linewidth',2)
3
grid on

4
ylabel('y')
5 xlabel('x')

title('Plot')
6

The graph

You must have noticed how complex it is to graph with PLOT. You need to
indicate the range of variation of the main variable, and you need to express the
first variable with respect to the second.

Example 2
Graphing this will be hard using PLOT, since it requires that you write y on one
side of the equation and x on the other side. But solving this equation will require
you use some guess on the other side to replace zero to help you be able to split
xy, and even then you will be plotting only one hypothesis. EZPLOT is the best of
the two options for cases like this one
E. Vectors in Matlab: Basic Operations
Tutorial45 MathLab

I will define a vector here as being a matrix with either a single column and many
rows or a single row and many columns.

The following are two vectors

Now that we are settled on what a vector is, let’s look how to manipulate vectors
using Matlab.

Vectors in Matlab
Create a vector in Matlab
How do you really create a vector in Matlab? We have learned lately how to
create matrices and manipulate them in Matlab. Playing with vectors is similar. It
goes like this:

If we would like the create the A and B vectors above, here is how we will go
about it

The code

A=[5,25,1,0,11,32]% The comma can be replace by a space

B=[4;1;1;7;8]

Find the largest component of a vector


To find the largest element of A and B, use the following code
max(A)

max(B)

which returns

We can use this to find the largest element of a vector. Assume you have a
vector with a thousand elements and can not go through each them to check
which one is the largest, this function will take the pain off your shoulder.

Find the smallest component


As the preceding function, we would use

min(A)

min(B)

Find the length of a vector


The length of a vector will tell you the number of elements the vector has. To find
the length of a vector, use

length(A)

length(B)

which returns
Sort in ascending order
We have learned the use of this function in Matlab in detailed in this post.

Sum elements of a vector


The sum function will simply sum all elements of a vector

The code

sum(A)

which returns

Find the mean value


The mean value formula is the following

This can also be written like this


To find the mean value of the vector A, use the following code

mean(A)

which returns

Find the standard deviation


To find the standard deviation, use the following code

std(A)

which returns

Find the median value of a vector


The median of a vector is nothing but the number separating the higher half from
the lower half. So the median of B with be 1, while the median of A will be 8.

To find the median value of the vector A, use the following code
median(A)

Which returns

Content you might like:


B. Plotting in Matlab – The Basics
Tutorial45 MathLab

We have recently used the EZPLOT technique to plot in Matlab, which is indeed
an easier technique to plot compared to the one we are going to make use of in
this post.

Plotting functions gives us a visual description of the behavior of the latter as we


change the system variable. And Matlab is THE TOOLS that will help you plot
with the less hassle possible while giving you a wide range of handiness of what
you will be capable of.

Plotting in Matlab
plot(A,B) plots vector B versus vector A and plot(Y) plots the columns of Y
versus their index.

Plotting example 1
Let’s plot one of the polynomial equations we have recently solved here.

Plotting this function in Matlab will look like the following

We first have to select the range of the variable and the incremental value of the
variable vector

Here is the code

x=-20:0.05:20;

y=x.^3+6*x.^2-20;

plot(x,y);

grid on;
The first line simply means that we want the variable x to start at -20 and to end
at 20, and it has to increase with a step of 0.05 from its initial value to its final
value. If you type the following code in Matlab (without the; at the end)

x=-20:0.05:20

Matlab will give you all the values of the element of the vector x.

The Second line tells Matlab to compute y for each value of x.

Grid on asks Matlab to display the grid while plotting y versus x.

Here is the plot

Plotting example 2
In this example, let’s plot 2 graphs in one plot. The following are the functions:
Here is the code

t=0:pi/50:3*pi;

xt=2*cos(t);

yt=sin(t);

plot(t,xt,'r',t,yt,'b');

grid on;

And the plot is the following.

The following line

plot(t,xt,'r',t,yt,'b');
Means that I want x(t) plot to be Red and y(t) plot to be Blue.

Use the line

Help PLot

or

Doc plot

To read more about PLOT in Matlab

Plotting example 3
Let’s plot a circle of 0.5 of radius

code:

Alpha=linspace(0,2*pi);

plot(0.5*cos(Alpha), 0.5*sin(Alpha),'LineWidth',2)

The plot:
‘LineWidth’,2 simply set the thickness of the plot to 2.

linspace(A, B) generates a row vector of 100 linearly equally spaced points


between A and B

Here are just the basics in plotting with Matlab, but with what you have just
learned you can start plotting and always remember that you can use Matlab
Help to learn more while using Matlab
B. Conditional Plotting in Matlab
Tutorial45 MathLab

By now, you should have learned the basics of plotting in Matlab using previous
post. In this session we want to look closer to how we can plot a conditional plot
using Matlab Here is an easy example of a conditional plot

plot f

Conditional plotting in Matlab


One of the way you can walk to easily plot f is the following Matlab code

1
x=-5:0.1:5;

2
for n=1:length(x)

3 if x(n)&lt;1

4 f(n)=x(n)^3;

5 else

f(n)=x(n)^2;
6
end
7
end
8
plot(x,f,'--r','linewidth',2)
9
which returns If
you were just to plot half of the graph each time and add up plots, the code would
look like

1
% Part 1

2
x=-5:0.1:1;

3 f=x.^3;

4 plot(x,f,'--b','linewidth',2);

5 % Part 2

x=1:0.1:5;
6
f=x.^2;
7
hold on;
8
plot(x,f,'--r','linewidth',2)
9
Content you might like
B. Graph the Equation by Plotting Points
Tutorial45 MathLab

Linear equations are some of the simplest equations and the easiest to plot.
These type of equations appear abundantly in most subareas of mathematics
and mostly in applied mathematics.

Graphing such equation by plotting points comes down to finding points


belonging to the graph using its equation.

It is pretty simple to find the points that will help you graph using equations and
all that is needed to do is to find at least 2 points and draw a straight line using
these two points.

Graph the equation by plotting points


let’s start with this simple example just to warm up

How do you plot the following equation?

Graphing the above equation will look like the following


let’s go the following example.

To find points on the line, we need to set one of the parameters to a certain value
and find its counterpart.

We will set x to a certain value and find what is the corresponding y for each of
the set value of x.
Plotting the graph, we will have the following
Note that to be sure of your result you can find the third point, and/or a first point
using the same technique we used above, and the point you find should lie on
the graph above.

You can as well choose to check your result using some online application like
C. Derivative in Matlab
Tutorial45 MathLab

In this post, we will pay some attention to one of the basic operations of calculus
which is Derivation.

We are not going to go into Derivative formulas here. We will right dive into
helping those who need to find a derivative jump into Matlab and quickly get what
they are looking for, without having to do it manually.

Matlab has a set of inbuilt functions that deal with such operations.

Content

Derivative in Matlab
Derivation of a constand in Matlab
Second derivative in Matlab
Partial derivative in Matlab
Derivative of a matrix in Matlab

Derivative in Matlab
Let’s consider the following examples

Example 1

Example 2

Example 3
To find the derivatives of f, g and h in Matlab using the syms function, here is
how the code will look like

syms x

f = cos(8*x)

g = sin(5*x)*exp(x)

h =(2*x^2+1)/(3*x)

diff(f)

diff(g)

diff(h)

Which returns the following (You can decide to run one diff at a time, to prevent
the confusion of having all answers displayed all at the same time)

Where we can depict the following

Derivative of a constant
We know that the derivative of any constant term is null but if for some reasons
you want to find the derivative of a constant using Matlab, here is how you need
to proceed.

constant = sym('5');

diff(constant)

Second derivative in Matlab


To find the second derivative in Matlab, use the following code

diff(f,2)

or

diff(diff(f))

Both will give the same result.

Partial derivative in Matlab


To find the derivative of an expression containing more than one variable, you
must specify the variable that you want to differentiate with respect to. The diff
function will help calculates the partial derivative of the expression
with respect to that variable.

Example

What is the partial derivative of f with respect to x?

Here is how to do it in Matlab

The code

syms x y
f = sin(x*y)

diff(f,x)

which returns

Derivative of a Matrix in Matlab


You can use the same technique to find the derivative of a matrix.

If we have a matrix A having the following values

The code

syms x

A = [cos(4*x) 3*x ; x sin(5*x)]

diff(A)

which will return


E. Write a Function That Find the Volume of a
3D Rectangle in Matlab
Tutorial45 MathLab

There is a function behind every Matlab code that performs a computational task,
and here is how you can create your own function that will help you go faster
while working with Matlab.

We will be creating a simple one line code function in this post, just to help you
have a glimpse into how creating functions in Matlab

Write a function in Matlab


Here is what you do when writing your own function in Matlab.

Open a new function file


Here is what appear on the next window
In Matlab, the section after the % is considered as comment (the section that
appears in green in the window above)

Here is how we need to structure our Matlab function

1
function [v] = vol(L,W,H)

2 % L is the length of the 3D rectangle

3 % W is the width of the 3D rectangle

4 % H is the height of the 3D rectangle

v= L*W*H;
5
end
6

You need to copy the whole code above and paste it in the file, Save the file with
the name vol.m and make sure not to change the directory Matlab will guide you
to.

Here is how it will look


How to use the Matlab function we have just created
Every time you will need to compute the such a volume, simply type the following
code

vol(L,W,H)

where L, W, And H will be real numbers.

Example
Let’s say, we need the volume of a 3D rectangle with L, W and H being
respectively 10, 3, 15, we can simply type:

vol(10,3,15)

And Matlab will call the function vol, compute the volume of the 3D rectangle and
display the following.
If you are working in an exercise where you will often need this volume, you can
just use this function instead of actually computing manually the volume each
time you need it. It might not look very important in this exercise, but when you
have a complex operation you need to perform often in Matlab, creating a
function doing it automatically will be time efficient and necessary.

Using this technique, you can create more complex functions in Matlab and have
an easier life while using them. Learn more about functions in Matlab.
B. Matlab Plot Colors and Styles
Tutorial45 MathLab

As we have already stated here, by writing help plot or doc plot in Matlab you
will be able to find the information we are about to give you down below.

Matlab plotting colors

The following are the letters you can add to your code to control the color of your
plot while plotting in Matlab.

 b blue
 g green
 r red
 c cyan
 m magenta
 y yellow
 k black
 w white

Let’s try some variants on the following example.

The default code to plot is:

1 x=-100:0.5:100;

2 y=x.^5-x.^2;

plot(x,y)
3

And the following will is the corresponding plot


Let’s twist the code a little to change the plot color

For the following code

1 x=-100:0.5:100;

2 y=x.^5-x.^2;

plot(x,y,'r')
3

The plot will look like


You must surely have grasped how to add the color code to get your graph to the
wanted color, and notice at the beginning of this post the different color and code
you can make use of while using this technique

Matlab plotting line style


Just like it is to change the color of your plot in Matlab, the same goes for
changing the line style, increasing the thickness of the line or some other aspect
of it

Let’s go ahead a plot the following code

1 x=-100:0.5:100;

2 y=x.^5-x.^2;

plot(x,y,'--r')
3

And the plot will be


or

1 x=-100:0.5:100;

2 y=x.^5-x.^2;

plot(x,y,'vr')
3

and the plot will be


Here is the code you can use to change the line style. (You can get that
information with help plot)

. point
o circle
x x-mark
+ plus
* star
s square
d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
— dashed
-. dashdot
: dotted
– solid

Here is how to change the thickness of the line of your plot in Matlab
The code

1 x=-100:0.5:100;

2 y=x.^5-x.^2;

plot(x,y,'m','LineWidth',2)
3

The plot

Here is another example which you can learn a lot from

The code

1 x = -pi:pi/10:pi;

2 y = tan(sin(x));
3 plot(x,y,'--rs','LineWidth',2,...

'MarkerEdgeColor','k',...
4
'MarkerFaceColor','g',...
5
'MarkerSize',5)
6

The Graph

Plotting multiple graphs on the same plot


One of the many ways to plot multiple functions on the same plot is to use hold
on or insert the corresponding equations in the plot code.

Here is a simple example

The code
1 x = -pi:pi/10:pi;

2 y1 = tan(sin(x));

3 y2 = tan(cos(x));

plot(x,y1,'--r',x,y2,'b','LineWidth',2)
4

The Plot

This can also be done the following way

The code

x = -pi:pi/10:pi;
1
y1 = tan(sin(x));
2
y2 = tan(cos(x));
3 plot(x,y1,'--r','LineWidth',2)

hold on
4
plot(x,y2,'b','LineWidth',2)
5

Matlab subplot
Subplot helps have plots side by side on the same sheet. Here is what Matlab
says about it. (Use Help Subplot)

subplot Create axes in tiled positions.


H = subplot(m,n,p), or subplot(mnp), breaks the Figure window into an m-by-n
matrix of small axes, selects the p-th axes for the current plot, and returns the
axes handle. The axes are counted along the top row of the Figure window,
then the second row, etc. For example,

subplot(2,1,1), PLOT(income)
subplot(2,1,2), PLOT(outgo)

Use the following code to try it out

x = -pi:pi/10:pi;
1
y1 = tan(sin(x));
2
y2 = tan(cos(x));
3
subplot(2,1,1)
4
plot(x,y1,'--r','LineWidth',2)

5
subplot(2,1,2)

6 plot(x,y2,'b','LineWidth',2)
7

The Plot

Plot legend and labels


You can learn more about this topic at matwork.com

Plotting
A. How to Convert Numbers From Polar to
Cartesian Form and Vice Versa
Tutorial45 MathLab

Among other Basic Matlab tutorials here on tutorial45, we are bringing this one
along as a quick tip to help you convert numbers from Polar to Cartesian in
Matlab.

We all know how to manually convert numbers from Cartesian to Polar and from
Polar to Cartesian, Here we will try to get introduced to the Matlab functions that
help you quickly convert numbers from Polar to Cartesian form and the vice
versa.

Convert from Polar to Cartesian form in Matlab


To convert a number from Polar to Cartesian form in Matlab, you can make use
of the pol2cart function. And it goes like this.

Let say we have the following number to convert

Where the radius and the angle are respectively

Here is how you will actually do it with Matlab

1 [RealPart, ImagPart]=pol2cart(-3*pi/4,4);

2 disp(['Real= ',num2str(RealPart),'; imag= ', num2str(ImagPart)]);


Which displays

Convert from Cartesian to Polar form


Converting from Cartesian to Polar is a little tricky, since the value of the angle
could be misinterpreted.

Let’s convert the following

in Polar form

To do this in Matlab, use the following.

1 [rad,mag]=cart2pol(2,3);

deg=rad*(180/pi);
2
disp(['mag= ',num2str(mag),'; rad= ',num2str(rad),'; deg=
3 ',num2str(deg)]);

Which prints

Here we converted the result from radiant to degree.

Hope you have learned a few new tricks today. Feel free to drop your concern
below if needed.
E. Matrix Multiplication – Matlab
Tutorial45 MathLab

Matrix multiplication is likely to be a source of a headache when you fail to grasp


conditions and motives behind them. Here, we will talk about two types of matrix
multiplication and how you can handle them both manually and using Matlab.

One of the best ways to test your understanding of the following is to work them
out manually and then using Matlab to check your result.

Matrix multiplication theory reminder


Let’s consider the following matrices.

Matrix product
Here is the formula for multiplying the above matrices, and I will highly
recommend you check the properties of Matrix multiplication and most
importantly the dimension agreement that is crucial between two matrices that
need to be part of a multiplication.

Generally speaking, if A is an n × m matrix and B is an m × p matrix, their matrix


product AB is an n × p matrix, in which the m elements across the rows of A are
multiplied with the m elements down the columns of B

Matrix multiplication element by element


In the other side, we have the element by element matrix multiplication, which is
rather a straightforward operation, here is the formula used.
It is simply the product of matrices, element by element, this type works only
when the dimensions of the matrices are equal. To be more specific, if A is an n
× m matrix, B has to be an n × m matrix for this to work.

Matlab Matrix Multiplication


The following code allows finding a matrix product in Matlab

C=A*B

and this one is the code to find the product of matrices, element by element

C=A.*B

Matrix multiplication examples


Example 1
If we keep the same logic as above while varying the value of A and B, but
knowing that C is the matrix product and D is the element by element matrix
multiplication.

Matlab code

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

B=[3 2 5;3 0 0; 1 1 2];

C=A*B

D=A.*B

Results
Example 2

Matlab code

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

B=[3 2;1 1];

C=A*B

Results

Example 3

Matlab code

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

B=[3 2;3 0; 1 1];

D=A.*B

Results
C. Matlab Polynomial: Division and
Multiplication
Tutorial45 MathLab

We have recently learned how to solve polynomial equations in Matlab, now we


are going to visit a trick that will help you learn how to do Division and
Multiplication of polynomial using Matlab.

Polynomial Division example

Polynomial Multiplication example

Matlab Polynomial
Multiplication of polynomial can be a very dreary task, so do division of
polynomial. Matlab use the functions conv and deconv to help you do these
tasks with the least commotion possible, and most importantly with the
assurance to find the right result the quickest way possible.

Let get on some examples, those will help easily learn how to make use of conv
(for multiplication) and deconv (for division).

Caution! We will not show you how to manually solve polynomial multiplication
and polynomial division manually here. Matlab will help you do it, but it will not
show you how to do it, so at this point we supposed you know how it is done.
Check how to do it manually if you do not.

Example 1

The code
s=[1 4];

t=[1 4 -3];

conv(s,t)

Which returns

Rewritten, it gives the following

Example 2

The code

c=[1 0 4];

u=[1 3];

[p,r]=deconv(c,u)% r is the remainder of the division

Which returns

Rewritten, it gives
A bit of clarity
Top-down conversion. Here we simply need to indicate the coefficient and their
position in the polynomial equation.

Bottom-up conversion. Here we need to read Matlab outputs and rewrite it the
way it is supposed to be, and it goes like this.

Remember you need to put a zero, in case an order is not represented in the
equation. See example below
B. Plotting Equations Using EZPLOT – Matlab
Tutorial45 MathLab

Plotting is a very important step in the study of a system since it helps


understand the behavior and the restrictions of the system with the less effort
possible.

Plotting an equation is not always an easy task especially if you have to work out
all the parameters manually, luckily nowadays there are tons of tools that help
plot equations.

Matlab is the most popular tools out there when it comes to the study of the
system, and in this post, we are going to work with some basic equations,
Matlab, and most importantly make use of EZPLOT for plotting equations.

Plotting equations in Matlab using EZPLOT


Ezplot Matlab example

To plot this equation in Matlab using the EZPLOT, We will write the equation the
following way

Now type the following code and press ENTER

ezplot('y-x^3-x^2+x-1',[-5 5 -5 5])

And you will obtain the following figure


If you would like to have more information about the command we just used, you
can find it by using the following code

doc ezplot

While using the EZPLOT, the structure of the code is the following

ezplot(fun,[xmin,xmax,ymin,ymax])

Where fun is the equation, xmin and xmax are respectively the lower and the
highest value of x, ymin and ymax the lowest and highest value of y. If the most
interesting part of the graph your are plotting is happening in a larger interval
than the one we just plotted, you may need to increase the value of xmin, xmax,
ymin and ymax.
E. Write a Matlab Function That Rotate a
Matrix by 90 Degrees
Tutorial45 MathLab

We have recently learned how to create functions in Matlab and make use of
them. Feel free to have a look at it to know how you will fully make use of the
following.

In this session, we are going to see how we can write few lines of code to ask
Matlab to help rotate a Matrix for us.

What do I mean by rotating a Matrix by 90 degrees?


Let’s consider the following Matrix

What we want to do is building a second matrix based on the matrix A, which is


going look like this

B is A rotated by 90 degrees.

In other words what we are trying to accomplish is the following

Rotate a Matrix
The code

N=length(A);

for i=1:N

for j=1:N

B(j,N-i+1)=A(i,j);

end

end

Here is the code you can use and test on a matrix of your choice. In order to
create a function that will handle just this task, you can use this code
appropriately.

Turn columns into rows and vice versa


Turning rows into columns and columns into rows while operating with matrices
is called determining the transpose of an already known matrix. If we have a
Matrix

and we want to convert rows into columns for it to look like

We simply need to use the following code in Matlab

B=A'

So we will say that A is a transpose of B.

Here is an example of a 3 X 3 matrix and its transpose


There are many already integrated functions in Matlab allowing you to gently play
with Matrices. Here are some Matlab Matrix operations you can make use of to
make your life easier.
E. Matlab Tricks: Creating an “Array”,
Modifying Matrix Elements
Tutorial45 MathLab

Among other tricks you can make use of while using Matlab, here are two tricks
that may help you have easier control while working with Matrices.

The first tip helps you create a list of elements in a certain order, and the second
will simply help you modify an element in an already existing matrix.

Here we go!

Creating an Array/table of elements


Just to have more light toward the direction we are heading to with this tip, we
will use the following example to show you what we are trying to build

We want to create something like the following

Example 1

Example 2

With these matrices, we are just trying to show that there is a certain pattern here
which is somehow obvious from the second example. Elements of the matrix are
equally spaced from a row/column to the next, for instance on the second
example, the first column is 1 to 5 spaced from one element to the other with 1.

Let’s now look at how you can create such Matrices in Matlab

The code
Example 1 (code corresponding to example 1)

n=(0:5)';

A=[n n.^2 2.^n]

Example 2 (code corresponding to example 2)

n=(1:5)';

B=[n n+1 n+2 n+3]

In the examples above, you can change the steps size to less than one, by
putting its value in between the digits in the first line of code

n=(1:0.5:5) % the step size is now reduced to half

%The Matrix will have more rows if you do use this

Modifying Matrix elements


From previous posts on Matrix manipulation in Matlab, we know how to access
specific elements in a Matrix, we can use the same technique to change the
values of elements in a matrix.

If we have a Matrix A looking like the following

We can, for instance, decide to change the second and third rows and the
second, third and fourth column to 1.
The code
B(2:3,2:4)=1

Here is what B will look like then

Posts you might like:


Matlab Matrix Operations
Write a Matlab function that rotates a Matrix by 90 degrees
Matrix multiplication – Matlab
Matlab tricks: Creating an “array”, modifying matrix elements
Sort a matrix in Matlab
Vectors in Matlab: Basic Operations
E. Sort a Matrix in Matlab
Tutorial45 MathLab

Sorting Matrices in Matlab are one of the easiest things to do when you happen
to know the language to use to order the software to do so.

In this example, we will deal with vectors, and we will write simple programs
sorting a vector in the ascending and descending order all for the objective to
make you understand the basics about sorting in Matlab.

Sort a Matrix in Matlab


There exist an inbuilt Matlab function that does sort Matrices for you, all you have
to do is call it when needed.

Let’s consider the following vector

Sorting A in ascending order will result to

and sorting A in a descending order will result to

Let’s see how that works in Matlab

Matlab code

1 A=[7 14 4 3 12 5 0 1];

2 B=sort(A) % You can also use B=sort(A,'ascend')

C=sort(A,'descend')
3
As simple as that.

let’s work more with a couple of examples, maybe those help practice you Matlab
skills

Example 1
Let’s write a small program that sorts any matrix of 5 elements. We want to give
the possibility to anyone to enter 5 elements, we will then put those elements in a
matrix, sort them and display the result.

Step 1: Ask element after element 5 times, and each time, put the element in the
matrix A, from position 1 to position 5

Step 2: sort the Matrix

Step 3: display the sorted matrix

Matlab code

1 for i=1:5

2 A(i)=input('Enter a number ');

3 end

B=sort(A);
4
B
5

Example 2
In the previous example, we predefined the number of elements of the vector, not
giving an option to users to use a vector with either more or less number of
elements than 5. Now we want to sort any vector. What we do is, ask the user to
provide the length of his vector first, so to be able to manipulate the for loop.

Matlab code
1
length=input('What is the length of your vector ');

2 for i=1:length

3 A(i)=input('Enter a number ');

4 end

B=sort(A);
5
B
6

As basic as this can be, we hope it has given you a glimpse of how you can play
with for loops in Matlab, and more importantly how you can sort matrices.

You might also like