Introduction to MATLAB – Step by Step Exercise
Large list of exercise: start doing now!
1 – 35: Basic (variables, GUI, command
window, basic plot, for, if, functions)
36 – 40: Medium (functions)
41 – 45: Medium (matrices)
46 – 51: Medium (plot)
52 – 55: Medium (integration)
56 – 60: Advanced (combined problems)
Introduction to MATLAB – Step by Step Exercise
1. Open MATLAB(student AMO/AIR)
2. Make sure that you recognize the Graphic User
Interface (GUI)
Introduction to MATLAB – Step by Step Exercise
3. Look for the command window, and use it as a
calculator:
• 2+2
• 2 * 2
• 22
•
•
Introduction to MATLAB – Step by Step Exercise
4. Create variables at the command window:
• a = 2
• b = 3
• a + b
• first_string = 'My name is '
• second_string =
'yournamehere,andpleasedontcopyandpastei
t,justwriteyourname,yourownname,thatonet
hatyourparentsgaveyoumanyyearsago'
• first_string + second_string
Introduction to MATLAB – Step by Step Exercise
5. Create variables based on other variables:
• c = a * 2
• d = cos(b)
• e = c + d
• r = 5
• A = 2 * pi * r
• C = 2 * pi * r
• x = 0
• curve_f = sin(x) + cos(x/3+1)
Introduction to MATLAB – Step by Step Exercise
6. Create vectors:
• vector_1 = [1 2 3 4 5 6 7 8 9 10]
• vector_2 = [12 13 14 15 16 17 8767826264]
7. Operation with vectors:
• vec_1 = [1 2 3]
• vec_2 = [7 8 9]
• vec_1 + 10
• vec_1 + vec_2
• vec_1 - vec_2
• times(vec_1, vec_2)
Introduction to MATLAB – Step by Step Exercise
8. Create column vectors
• colu_1 = [1; 2; 3; 4; 5]
• colu_2 = [23; 24; 25; 26]
• colu_3 = ['aa'; 'bb'; 'cc'; 'dd']
9. Other ways to create vectors:
• z = zeros(5,1)
• zz = zeros (1, 5)
• zzz = [0: 1:10]
• zzzz = [-8763: 430.2265 : 5634.23]
Introduction to MATLAB – Step by Step Exercise
10. Creating Matrices:
• matr_1 = [1 2 3; 4 5 6; 7 8 10]
• matr_2 = ['lala ' 'lele '; 'lili ' 'lolo
'; 'lulu ' 'lålå ']
11. Operation with Matrices:
• matr_1 + 10
• sin(matr_1)
• matr_1'
• inv(matr_1)
• identity_matrix = matr_1 * inv(matr_1)
• element_multiplication = matr_1.*matr_1
Introduction to MATLAB – Step by Step Exercise
12. Accessing elements in the Matrix:
• matr_1(1,2)
• matr_1(8)
• matr_1(1:3,2)
• matr_1(3,:)
13. Check that your variables are at the workspace:
Introduction to MATLAB – Step by Step Exercise
14. Create and save a script (no spaces, MATLAB
folder):
Introduction to MATLAB – Step by Step Exercise
14. Start your script by clearing the variables ans
summing 2 + 2:
1. clear
2. 2 +2
15. Run your script and check the answer (ans) on
the command window:
Introduction to MATLAB – Step by Step Exercise
16. Create a vector in your script with a list of dates:
1. clear
2. dates = [1015 1066 1660 1814 1905 2014]
17. Realize that, by putting ; at the end of the line the
command does not appear at the command window:
1. clear;
2. dates = [1015 1066 1660 1814 1905 2014];
Introduction to MATLAB – Step by Step Exercise
18. Sum up all the ages:
1. clear
2. dates = [1015 1066 1660 1814 1905 2014];
3. sum_all = sum(ages);
19. Save the number of dates inside the vector
"dates" into a variable ":
1. clear;
2. dates = [1015 1066 1660 1814 1905 2014];
3. sum_all = sum(dates);
4. how_may_dates = length(dates);
Introduction to MATLAB – Step by Step Exercise
20. Write a comment
5. % This is a comment
6. % Realize that from now the code is your
own, so you don't need to follow the same line
that I write here.
21. Calculate the average of the dates by dividing
the sum by the number of elements
average_dates = sum_all/how_may_dates;
22. Display in the command line a text, and later the
average
disp('The average is: ');
disp(average_dates )
Introduction to MATLAB – Step by Step Exercise
23. Plot the sin(dates)
f_x = sin(dates);
plot (dates, f_x);
24. Plot (dates)2 / (150000) – 0.02* (dates) + 12:
ff_x = (dates).^2/(150000) - 0.02*(dates) +12
plot (dates, ff_x);
25. Use "hold on" between the two plots :
ff_x = (dates).^2/(150000) - 0.02*(dates) +12;
plot (dates, ff_x);
hold on
f_x = sin(dates);
plot (dates, f_x);
Introduction to MATLAB – Step by Step Exercise
26. Realize that we can transform numbers to string and
use it to display test inside a "disp" as a vector
disp(['Dois mais Dois igual a: ' num2str(4)]);
27. Create a for to read each element of the vector and
display its value
for i = 1:how_may_dates
disp(['The date is: ' num2str(dates(i))]);
end
Introduction to MATLAB – Step by Step Exercise
28. Create a "if" to check if a year is before, equal or
after year 1800
year = 1750;
if year < 1800
disp('Year is before 1800');
elseif year == 1800
disp('Year is 1800');
else
disp('Year is above 1800');
end
Introduction to MATLAB – Step by Step Exercise
29. Incorporate and modify the "if" inside your "for", to
check if a date is before, after or equal 1814
for i = 1:how_may_dates
disp(['The date is: ' num2str(dates(i))]);
if dates(i) < 1814
disp('Before 1814');
elseif dates(i) == 1814
disp('It is 1814!');
else
disp('After 1814');
end
end
Introduction to MATLAB – Step by Step Exercise
29. Incorporate and modify the "if" inside your "for", to
check if a date is before, after or equal 1814
for i = 1:how_may_dates
disp(['The date is: ' num2str(dates(i))]);
if dates(i) < 1814
disp('Before 1814');
elseif dates(i) == 1814
disp('It is 1814!');
else
disp('After 1814');
end
end
Introduction to MATLAB – Step by Step Exercise
30. Adapt your code from 29 to solve the example from
last week:
Create a a code that checks if you can buy alcohol in
Norway, the type of alcohol, if you can enter in a night club,
and if you can teach your friend to drive:
• age < 18 – None
• 18 < age < 20 – Alcohol below 22%, no clubbing nor
teach
• 20 < age < 21 Alcohol above 22%, but no clubbing nor
teaching
• 21 < age < 25 – Alcohol above 22% and clubbing, but
no teaching
• age > 25 – All allowed
Introduction to MATLAB – Step by Step Exercise
31. Function: a named section of a program that
performs a specific task. Realized that "sum", "length"
and "times" is a function
sum([1 2])
length([1 2])
times([2],[2])
Introduction to MATLAB – Step by Step Exercise
32. Study the basic command to create a function:
• function to add any two numbers:
what the
what the
function to function
function returns!
create a function! receives!
function [sum_number] = add_numbers(x,y)!
!
"sum_number = x+y;! name of the function!
!
end!
variable that receives operation/task
the operation! performed by
the function!
Introduction to MATLAB – Step by Step Exercise
33. Based on 32, created a function that adds two
numbers called "add_numbers".
34. Use your "add_numbers:
add_numbers(2,3)
add_numbers(10,32)
35. Create a new function, that multiply 2 numbers,
and use it
36. Create a function that transform years in days
Introduction to MATLAB – Step by Step Exercise
37. Create a function that check if a number is above
or bellow 1814
38. Create a function that receives a vector and
display all the elements of this vector
39. Create a function that calculates sigma for a
cantilever given your P, L and h
function [sigma] = tension(P,L,h)!
"sigma = P*L*6/(h^3);!
end!
Introduction to MATLAB – Step by Step Exercise
40. Create a function calculate the area (I) between
two points (a,b) by the trapezoidal rule:
Introduction to MATLAB – Step by Step Exercise
41. Create matrices d, e and f by concatenating
vectors a, b and c:
>> a = [1 2];
>> b = [3 4];
>> c = [5;6];
>> d = [a;b];
>> e = [d c];
>> f = [[e e];[a b a]];
Introduction to MATLAB – Step by Step Exercise
42. Consider the a = 2, b=4, c=6, d=9 and calculate
2A in MATLAB given :
43. Consider θ = pi/6, m’=4, n’=2, calculate the value
of [m,n] for:
Introduction to MATLAB – Step by Step Exercise
44. Solve the problem from 1st day, calculating how
much sales the shop makes on each day in matrix
operations:
Matrix multiplication example:
• Beef pies cost $3 each
• Chicken pies cost $4 each
• Vegetable pies cost $2 each
They are sold in 4 days
the value of sales for Monday is calculated as:
• Beef pie value + Chicken pie value + Vegetable pie value
= $3×13 + $4×8 + $2×6 = $83
= ($3, $4, $2) • (13, 8, 6) = $3×13 + $4×8 + $2×6 = $83
Introduction to MATLAB – Step by Step Exercise
45. Create a multi-dimensional matrix based on the
figure below:
Introduction to MATLAB – Step by Step Exercise
46. Obtain the following plot:
t=0:0.1:10;
y1=sin(t);
y2=cos(t);
plot(t,y1,'r',t,y2,'b--');
x=[1.7*pi;1.6*pi];
y=[-0.3; 0.7];
s=['sin(t)';'cos(t)'];
text(x, y, s); % Add comment at (x,y)
title('Sin and Cos'); % Title
legend('sin','cos') % Add legend
xlabel('time') % the name of X-axis
ylabel('sin & cos') % the name of Y-axis
grid on % Add grid
axis square % set figure as a shape
of square
Introduction to MATLAB – Step by Step Exercise
47. Obtain the similar curving fit data using polyfit
and polyval:
x=[14.2, 16.4, 11.9, 15.2, 18.5, 22.1,
19.4, 25.1, 23.4, 18.1, 22.6,
17.2];
y=[215, 325, 185, 332, 406, 522, 412,
614, 544, 421, 445, 408];
coeff = polyfit(x,y,1);
y_fit = polyval(coeff,x);
plot(x,y,'r+',x,y_fit), grid on,
xlabel('x-data'), ylabel('y-data'),
title('Basic curve-fitting'),
legend('Original data','Line of
best fit','Location','SouthEast')
Introduction to MATLAB – Step by Step Exercise
48. Obtain the following 3D plot:
t=0:pi/50:10*pi;
plot3(sin(t),cos(t),t, 'r.'),grid
on,xlabel('x'),
ylabel('y'),zlabel('z'),
title('3D helix')
Introduction to MATLAB – Step by Step Exercise
49. Define a meshgrid and plot the following
3D function:
where a = 3, c = 0.5, -1 < x < 1 and -1 < y < 1
x=linspace(-1,1,50);
y=x;
a=3
c=0.5
[xx, yy] = meshgrid(x,y);
z = c*sin(2*pi*a*sqrt(xx.^2+yy.^2));
surf(xx,yy,z), colorbar, xlabel('x'), ylabel('y'),
zlabel('z'),title('f(x,y)=c sin(2 \pi a \surd(x^2+y^2))')
figure;
mesh(xx,yy,z), colorbar, xlabel('x'), ylabel('y'),
zlabel('z'), title('f(x,y)=c sin(2 \pi a \surd(x^2+y^2))')
Introduction to MATLAB – Step by Step Exercise
50 Plot the following 3D curves using the plot3 function
a) Spherical helix
where c = 5 and 0 < t < 10π
b) Sine wave on a sphere
where a = 10, b = 1, c = 0.3, and 0 < t < 2π
Introduction to MATLAB – Step by Step Exercise
51 Plot the following 3D curves using the surf function
Sine surface
where 0 < u < 2π and 0 < v < 2π
Elliptic torus
where r1 = r2 = 0.5, t = 1.5, 0 < u < 10π and 0 < v < 10π
Introduction to MATLAB – Step by Step Exercise
52. Describe each part from the trapezoidal
function from MATLAB
Introduction to MATLAB – Step by Step Exercise
53. Remind about differential equations, and
how
Introduction to MATLAB – Step by Step Exercise
54. Using the trapezoidal function plot and integrate
(0-pi/2) for f(x) = sen(x) and f(x) = cos(x)
x = 0:pi/100:pi;
y = sin(x);
trapz(y,x) % returns 1.9338
plot (x,y,'k-*')
%for the lines
for i=1:length(x)
line([x(i) x(i)], [0 y(i)])
end
Introduction to MATLAB – Step by Step Exercise
55. Using the trapezoidal function plot and integrate
the number of passengers
Introduction to MATLAB – Step by Step Exercise
56. Plot the bell-shaped function f(x), x range [0,1],
varying α in [1.5, 2, 4, 9 ]
Using the trapezoidal function, calculate the area
from the range x [0.2, 0.8] for all four α
f(x) = 4^α * x^(α - 1) * (1 - x)^(α - 1)
Introduction to MATLAB – Step by Step Exercise
57. Plot the following solids in revolution (cylinder)
function and calculate its volume
a) b)
A = meshgrid(linspace(0, 2*pi, 50),
linspace(0, 2*pi, 50)) ;
X = 3 .* cos(A);
Y = 3 .* sin(A); t = 0:pi/10:2*pi;
Z = meshgrid(linspace(-5, 5, 50), [X,Y,Z] =
linspace(-5, 5, 50))'; cylinder(2+cos(t));
surf(X, Y, Z), axis equal surf(X,Y,Z)
axis square
Introduction to MATLAB – Step by Step Exercise
58. Design a group of cranes, varying square cross
section and load for L = 3m. Check if crane
collapses (σmax = 250MPa)
σ = PL*6/h3
Consider:
load_vector = 100:100:1000!
section_h_vector = 10:10:100!
Introduction to MATLAB – Step by Step Exercise
59. Giving the cities represented by letters A to F, and
the distance among them represented by the value in
the connecting line, calculate the shortest order to
visit ALL the cities
Travel salesman problem solution:
• Acquire data from every city
• Calculate distance between all the
cities (A-B, A-C, ... E-F)
• Try every possible combination
• Answer is the combination with
the shortest sum
Introduction to MATLAB – Step by Step Exercise
60. Sketch a problem of your own which you think
that MATLAB can help to solve