Euler Method Matlab Code - Belajar
Euler Method Matlab Code - Belajar
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
1
function [v] = vol(L,W,H)
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.
vol(L,W,H)
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.
Trigonometric sine
Matlab code
sin(pi)
Trigonometric cosine
Matlab code
cos(pi)
Trigonometric tangent
Matlab code
tan(3*pi/2)
Matlab code
asin(1)
Matlab code
acos(0.5)
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)
Matlab code
rem(5,2)
which returns
Matlab code
round(2.9)
Which returns
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
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
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.
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
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?
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.
B=[8;3];
X=inv(A)*B
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
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
B=[1;2;13];
X=inv(A)*B
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.
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
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;
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
The code
syms 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
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.
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)
4
tb=1; %Second time
5 target_ub=0; % target
12
for (j=2:50) % stop after 50 iteration even if the accuracy is not
13 reached
20
25
26
The Plot
A. Left Division vs Right Matrix Division –
Matlab
Tutorial45 MathLab
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
Matlab code
1 A=[1 2 ; 2 2];
2 B=[3 2 ; 1 1];
which returns
This technique can be used to quickly compute the solution of the equation
will be written
1 A=[1 2 ; 2 2];
2 B=[3 2 ; 1 1];
which returns
Where
The code
1 A./B
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
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.
Where
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
roots([1 0 -4])
roots([1 6 0 -20])
Do not forget to add 0 between 6 and -20 since the first-order coefficient is zero
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:
we will write
A=[1 1 -2;2 2 1;2 1 1]
size(A)
If we type
size(B)
A+C
A./C
inv(A)
det(A)
Define a Matrix with Random elements
To create a Matrix with Random element in Matlab, use
rand(3,2)
diag(A)
diag(A,1)
diag(A,-1)
A'
or
transpose(A)
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)
C(:,3)
Multiply Matrices
To multiply A X B, A and B being two distinct matrices, A and B has to obey
these conditions.
A*B
A.*B
To create a Matrix with all elements equal to zero, use the following code
G=zeros(3,4)
To create a Matrix with all elements equal to one, use the following code
O=ones(4,5)
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)')
The Graph
Example 2
The code
1 f=ezplot('sin(x*y)')
The graph
Plotting with PLOT
Example 1
The code
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.
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
B=[4;1;1;7;8]
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.
min(A)
min(B)
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.
The code
sum(A)
which returns
mean(A)
which returns
std(A)
which returns
To find the median value of the vector A, use the following code
median(A)
Which returns
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 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.
We first have to select the range of the variable and the incremental value of the
variable vector
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.
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;
plot(t,xt,'r',t,yt,'b');
Means that I want x(t) plot to be Red and y(t) plot to be Blue.
Help PLot
or
Doc plot
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.
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
1
x=-5:0.1:5;
2
for n=1:length(x)
3 if x(n)<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.
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.
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)
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)
diff(f,2)
or
diff(diff(f))
Example
The code
syms x y
f = sin(x*y)
diff(f,x)
which returns
The code
syms x
diff(A)
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
1
function [v] = vol(L,W,H)
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.
vol(L,W,H)
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.
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
1 x=-100:0.5:100;
2 y=x.^5-x.^2;
plot(x,y)
3
1 x=-100:0.5:100;
2 y=x.^5-x.^2;
plot(x,y,'r')
3
1 x=-100:0.5:100;
2 y=x.^5-x.^2;
plot(x,y,'--r')
3
1 x=-100:0.5:100;
2 y=x.^5-x.^2;
plot(x,y,'vr')
3
. 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
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
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
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(2,1,1), PLOT(income)
subplot(2,1,2), PLOT(outgo)
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
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.
1 [RealPart, ImagPart]=pol2cart(-3*pi/4,4);
in Polar form
1 [rad,mag]=cart2pol(2,3);
deg=rad*(180/pi);
2
disp(['mag= ',num2str(mag),'; rad= ',num2str(rad),'; deg=
3 ',num2str(deg)]);
Which prints
Hope you have learned a few new tricks today. Feel free to drop your concern
below if needed.
E. Matrix Multiplication – Matlab
Tutorial45 MathLab
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 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.
C=A*B
and this one is the code to find the product of matrices, element by element
C=A.*B
Matlab code
A=[1 2 2; 1 0 5; 3 1 2];
C=A*B
D=A.*B
Results
Example 2
Matlab code
C=A*B
Results
Example 3
Matlab code
D=A.*B
Results
C. Matlab Polynomial: Division and
Multiplication
Tutorial45 MathLab
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
Example 2
The code
c=[1 0 4];
u=[1 3];
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 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.
To plot this equation in Matlab using the EZPLOT, We will write the equation the
following way
ezplot('y-x^3-x^2+x-1',[-5 5 -5 5])
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.
B is A rotated by 90 degrees.
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.
B=A'
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!
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)';
n=(1:5)';
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
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
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.
Matlab code
1 A=[7 14 4 3 12 5 0 1];
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
Matlab code
1 for i=1:5
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
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.