2. Course Outline
❑Basic setup
❑Variables and arrays
❑For Loops
❑If Statements and Decision Making
❑User Input and Pausing
❑Saving and Loading Variables
❑Plotting
6. Variables and Arrays
❑A variable is something that holds a number for us to carry out
computation with.
❑Variables can be a single number or a multitude of numbers called
an array or matrix.
7. Variables and Arrays
❑We can use the colon to generate a vector, which is series of
numbers, from a start point to an endpoint in steps of 1 or
increments we set.
❑Methods of addressing an individual element or number in an
array, an entire row or rows, column or columns are described in the
following examples.
9. Matrices/Arrays
%% x, y and z are our variables , note that to declare a matrix
we use square brackets, a semicolon ends the row, since we have 3
entries we have 3 columns.
x=[1,1,1];
y=[2,2,2];
z=x+y
10. Matrices/Arrays
%% a, b and c are our variables, a semicolon ends the row, now we
have 3 rows.
a=[1;1;1;];
b=[2;2;2;];
c=a+b
11. Basic Colon Use
%% here we define an array x=[1,2,3] using the colon
x=[1:3]
12. Basic Colon Use
%% here we define an array x=[5,10,15] the number between the
colons is the step we increment by
y=[5:5:15]
13. Methods to Address Array Values
% We define our variable x below
x=[1,2,3;
4,5,6;
7,8,9;];
%% We setup a variable C to take the value 3 from the first row and third column
using the format new_variable=other_variable(Row_Number,Column_Number).
C=x(1,3)
% Answer C=3.
14. Methods to Address Array Values
% We define our variable x below
x=[1,2,3;
4,5,6;
7,8,9;];
%% Below we take the third row and assign its values to D, By using the colon in
the columns spot we have selected all columns in the third row.
D=x(3,:)
% Answer D = 7,8,9.
15. Methods to Address Array Values
% We define our variable x below
x=[1,2,3;
4,5,6;
7,8,9;];
%% We can do the opposite and select the third column and all rows.
E=x(:,3)
% Answer E = 3,6,9.
16. Methods to Address Array Values
% We define our variable x below
x=[1,2,3;
4,5,6;
7,8,9;];
%% Getting a little fancier we can select the last two rows and the first two
columns.
F=x(2:3,1:2);
% Answer F = [4,5;
% 7,8;];
18. For Loops
❑In programming we find ourselves in situations where we need to
input or calculate a lot of data in a sequential or iterative fashion.
❑We use a variable called an index. The index changes its value on
each cycle of the loop. These cycles are referred to as iterations. The
lowercase i in the examples are the index of a loop, you may use any
letter or word you like to name your index.
19. For Loops to Address Arrays
%% We set a loop that runs ten times that calculates x added to the current index, by using
(i) next to y we can save each computed value as an addressable element in the array y.
x=10;
%% i increases in value from 1 to 10 in steps of 1,
% when i =1 y(i)=y(1) Which is the first element of the array y
% y(1)=x+1 This means we assign the value x+1 to the array element y(1).
for i=1:10
y(i)=x+i
end
21. If Statements and Decision Making
❑When programming we often find ourselves in a position where we need to write code that
can make decisions. The simplest way to do this is by means of an If statement.
❑An If statement allows a piece of code to run if certain conditions are met. A few simple tricks
are conditions based on terms being greater than, less than or equal to certain values.
❑Else statements can be used in conjunction with If statements, if the If statements condition is
not met, you can set an else statement to run some code or provide subsequent If statements
beneath that Else statement to run code under certain conditions.
22. If Statements Using Greater Than
% Here we have a piece of code that iterates from 1 to 10, it counts the
number of values where i>3.
Numbeber_of_values_over_3=0;
for i=1:10
if i>3
Numbeber_of_values_over_3=Numbeber_of_values_over_3+1;
end
end
%% Answer Numbeber_of_values_over_3 = 7.
23. If Statements Using Less Than
% Here we have a piece of code that iterates from 1 to 10, it counts the number
of values where i<5.
Numbeber_of_values_under_5=0;
for i=1:10
if i<5
Numbeber_of_values_under_5=Numbeber_of_values_under_5+1;
end
end
%% Numbeber_of_values_under_5 = 4.
24. If Statements Using AND
% Here we have a piece of code that iterates from 1 to 10, it counts the
number of values where i<9 AND i>6, thereby counting the numbers between 9 and 6.
Numbeber_of_values_under_9_but_over_4=0;
for i=1:10
if i<9 && i>6
Numbeber_of_values_under_9_but_over_4=Numbeber_of_values_under_9_but_over_4+1;
end
end
%% Numbeber_of_values_under_9_but_over_4 = 2.
25. Else Statements and Using Equals To
x=[1,1,2,2,2];
Number_of_ones=0;
Number_of_twos=0;
for i=1:5
if x(i)==1
Number_of_ones=Number_of_ones+1;
else
Number_of_twos=Number_of_twos+1;
end
end
%% Answer Number_of_ones = 2; Number_of_twos = 3;
26. Using Multiple If and Else Statements
x=[1,1,2,2,3];
Number_of_ones=0;
Number_of_twos=0;
Number_of_threes=0;
for i=1:5
if x(i)==1
Number_of_ones=Number_of_ones+1;
else
if x(i)==2
Number_of_twos=Number_of_twos+1;
else
if x(i)==3
Number_of_threes=Number_of_threes+1;
end
end
end
end
%% Answer Number_of_ones = 2 ; Number_of_twos = 2; Number_of_threes=1;
28. User Input and Pausing
❑In programming you may want to prompt user input as you run
your code instead of predefining everything.
❑Sometimes we may want to view things in a controlled fashion. By
using pause we can view changes on each iteration and see how they
develop things.
29. User Input
%% Here we establish a loop that runs for 1000 intervals, if the user inputs 1 they escape
the loop, i prints out each time denoting the interval number.
for i=1:1000
N = 'Would you like to end this loop? Enter 1 ';
N = input(N)
i
if N== 1
break
end
end
%%
30. Pausing
%% Here we establish a loop that runs for 100 intervals, on each interval the
loop prints a value of x and is then paused, press the spacebar to continue.
for i=1:100
x=i^2
pause
end
%% A useful trick to escape a long loop is to press control and C together in the
command window.
32. Saving and Loading Variables
❑Once you have completed some calculations, you may want to save
your variables to a file and read them in later rather than carrying
out the calculations all over again the next time you boot up your
computer.
❑MATLAB® can save and load variables in a variety of formats, an
example of how to do that with text files is shown in the following
example.
33. Saving and Loading a Variable
%% Here we establish the Array a.
a=[1:1:5;
2:2:10;];
%% Here we save the Array a as a text file
dlmwrite('filename.txt',a,'delimiter',' ');
%% Here we load the values from that text file into a variable M.
M = dlmread('filename.txt')
%%
35. Plotting
❑Plotting is the act of drawing a figure with your data, it helps you
visualize the numbers you are working with.
❑There are several nuances with plotting that we will go through
step by step.
36. Basic Plot of a Line
%% Below we establish the variable a and then plot it
a=[1,2,3,4,0,6,7,8,12,-3];
plot(a)
%%Note that plot as well as other functions are case sensitive,
if
%%you spelt Plot instead of plot you would get an error message
40. Notes
❑You will find yourself if situations where you will have x and y data that you want to plot to get
a line with some meaning.
❑One caveat to this is that the arrays holding x and y data must have the same number of
entries, or you will get an error message.
❑Next, we’ll look at examples that plots a few variables, it will cover labelling axis, adding a
legend, changing font size and setting the color for our lines.
41. Plotting Many Variables at Once
x=[1:10];
car1=[1,2,3,4,5,6,7,8,9,10];
car2=[3,3,3,3,3,3,3,3,3,3];
car3=[10,9,8,7,6,5,4,3,2,1];
plot(x,car1,'k',x,car2,'b',x,car3, 'r')
legend('Car 1','Car 2', 'Car 3')
xlabel('Time','FontSize',28)
ylabel('Speed','FontSize',28)
title('My First Title','FontSize',28)