York University Itec2600 by Amanda Tian

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

York University ITEC2600 By Amanda Tian

10.2 multiple for loop


In the following multiple “for” loop example, we create a 3 by 4 matrix.

i j j=1 j=2 j=3


i=1 A(1, 1) = 1*1 A(1, 2) = 1*2 A(1, 3) = 1*3
i=2 A(2, 1) = 2*1 A(2, 2) = 2*2 A(2, 3) = 2*3
i=3 A(3, 1) = 3*1 A(3, 2) = 3*2 A(3, 3) = 3*3

>> for i = 1:3 % i = 1, 2, 3


>> for j = 1:4 % j = 1, 2, 3, 4
>> A(i,j) = i*j ; % resulted A is a 3 by 4 matrix.
>> end
>> end
>> A

A=

1 2 3 4
2 4 6 8
3 6 9 12

10.3 while loop


Syntax:
while expression
statements
end
In the following example, we display i value when i <= 5
>> i = 0;
>> while (i <= 5) % when i <= 5 is true, the loop continuous
>> i = i + 1; % increase i value by 1.
>> disp(i); % display value of i
>> end
1
2
3
4
5
6
Note that in above example the last i value displayed is 6 not 5. That is because we put “disp(i)” below “i = i+1”. Hence when i
= 5, the logical condition expression is still true, then i = 5+1 = 6, hence the value displayed is 6. To modify it to display 5 at the
end, we can do the following:
>> i = 0;
>> while (i <= 5) % when i <= 5 is true, the loop continuous
>> disp(i); % display value of i
>> i = i + 1; % increase i value by 1.
>> end
0
1
2
3
4
5

10.4 Break
Note:
• break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute.
• In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end
of that loop.

The following while loop is an infinite loop (a loop that never ends on its own). It never stops as the logical condition expression
“ind” is always true. To stop an infinite loop. We can click ctrl + c at the command window.
York University ITEC2600 By Amanda Tian

>> i = 0;
>> ind = true;
>> while ind % ind is true always, the value is not changed within the loop
>> i = i + 1;
>> disp(i)
>> end
We can add “break” to this loop to stop it at some moment.
>> i = 0;
>> ind = true;
>> while ind
>> disp(i)
>> i = i + 1;
>> if i > 5 % we break the loop when i > 5.
>> break
>> end
>> end
0
1
2
3
4
5

10.5 Other “for” loop examples.


We apply the “for” loop to our test1 question Q6 e). For a table defined below, we want to get the month in which the price is
smallest.
Month Price Count
1 99 10
2 58 30
3 94 20
4 66 27
5 87 5
6 91 1

If we do not use loop this question can also be solved by code:


>> T(T.Price == min(T.Price),'Month' )

ans = table
Month
_____
2

For practice purpose, we will do it using “for” loop. The idea here is that we assume the first row has the smallest price, hence we
initial m = 1. That is, we assume the first row price is the lowest. Then we compare the 2nd row price with the smallest price (for
now it is the first row price: 99). If the 2nd row price (58) is less than the first row price (99) then we replace the value of m by 2
(2 is the 2nd row index), otherwise the value of m will stay to 1. We repeat the comparison process for 3rd row, 4th row…, until the
last row of the data. In this compare process the row with the smallest price will be selected, and the index will be stored in
variable m.
>> Month = [1; 2; 3; 4; 5; 6];
>> Price = [99; 58; 94; 66; 87; 91];
>> Count = [10;30; 20; 27; 5; 4];
>> T = table(Month, Price, Count);

>> m = 1;
>> for i = 2:size(T,1) % i = 2, 3, 4, 5, 6 in this case.
>> if T.Price(i) < T.Price(m)
>> m = i;
>> end
>> end
>> T(m, 'Month')

ans = table
York University ITEC2600 By Amanda Tian

Month
_____
2

Although the above code has successfully found the smallest price month: 2, it does not consider the case when a tie exists.
Consider the following data, where months: 2, 4, 5 all have the smallest price. If we run the previous code, only month 2 will be
selected. Months: 4 and 5 will be ignored. To improve it, we need to consider the situation when the current row price is equal to
the smallest price, and manage to store multiple values to m. That is, we may need m to be a vector or a cell. This will be left as
an exercise question for your own practice.
Month Price Count
1 99 10
2 58 30
3 94 20
4 58 27
5 58 5
6 91 1

11. Self-defined function


For create and call self-defined function, there are some important note:
• If the function is saved in a single .m script/file, We can call the function by running the file’s name in other script. The
function name does not need to be the same as the file name. But if multiple functions are saved in one single .m script,
then only the first function can be called from other script. The following functions only work if they are sub-functions
of the first function.
• If the main code and the self-defined function are saved in the same .m script/file. Then the function should be at the
bottom of the script. We can click the <Run> button (or F5) to run the whole script. F9 line by line running does not
work in this situation.
Here is some example about self-defined function.
We create a script which name is “myfun.m”, with the following codes.
x = 1:10;
n = length(x);
avg = myMean(x,n) % call myMean() function to calculate average value for vector x.
m1 = vectMult(x,1) % call vectMult() function to calculate the products of vector x.
m2 = vectMult(x,0) % call vectMult() function to calculate the summation of vector x.
m3 = vectMult(x,2) % call vectMult() function with wrong input ind = 2,

function a = myMean(v,n) % v, n are inpute parameters, a is the output paramter.


a = sum(v)/n; % calculate the average of the vector v and save the value to variable a
end

function m = vectMult(v, ind) % v, ind are input parameters. m is the output parameter.
if ind == 1
m = prod(v); % multiplication for vector v elements
elseif ind == 0
m = sum(v); % summation for vector v elements
else
disp("wrong input");
m=0;
end
end

Then we can click the <Run> button to run the code, and we have the following output in the command window.
>> myfun % the name of the .m script

avg =
5.5

m1 =
3628800
York University ITEC2600 By Amanda Tian

m2 =
55

wrong input

m3 =
0
We can also run this script by
• Key in “myfun” at the command window and <enter>
• Write a single line of code: “myfun” in any other .m script, highlight and click F9.

Here is another example. We create a script with name “mySquare.m” and with the following code.
function y = mySquare(a) % input parameter a, output parameter y.
y = a^2;
end
Then we can call this function mySquare() by
>> sq = mySquare(3) % call a function in another script .m file.
sq =
9
If we put two functions in one script, only the first one can be called. See example “mySquare1.m”, with code:
function y = mySquare1(a)
y = myPower(a)^2;
end

function y = myPower(a)
y = a^3;
end
When we try to call these two functions from other .m script:
>> sq1 = mySquare1(3) % only the first function can be called, which is taken as the main function.

sq1 =
729

>> pw = myPower(3) % Get error when calling the other function.


Undefined function or variable 'myPower'.

12 Plot/graph
12.1 2-D plot
plot() function in Matlab plot point using the x-y coordinators. Below is the example. For code plot([2, 4, 3, 5] , 'Marker','o') , [2,
4, 3, 5] correspond y coordinators. x coordinators are by default 1, 2, 3, 4 ….
>> plot(2, 3, 'Marker','o') % plot a point (2, 3) in the 2-d space.
>> plot([2, 4], [3, 5], 'Marker','o') % plot two points (2, 3), (4, 5) in the 2-d space
>> plot([2, 4, 3, 5] ], 'Marker','o') % plot a list of numbers which are for y-axis values.
York University ITEC2600 By Amanda Tian

In the following examples, we plot a function y= sin(x). We can chose to plot a curve or plot only points by specifying the Name
value pair arguments: ‘LineStyle’ and ‘Marker’.
>> x = 1:0.1:10; % create a vector which is a list of numbers
>> y1 = sin(x); % another vector corresponding to y1 = sin(x) function
>> plot(x, y1) % plot with two vectors, one vector for x-axis coordinate, another vector for y axis coordinate
>> plot(x, y1, 'LineStyle','none', 'Marker','*') % plot with only points without line. By default Matlab will add line
between points by order

The following examples shows how to set arguments to adjust color, lines style, marker style and marker size.
plot(x, y1, 'Color','red') % specify the plot color
plot(x, y1, 'LineStyle','-.', 'Color','red') % specify the line style
plot(x, y1, 'Marker','+') % add marker at points, and specify marker's type
plot(x, y1, 'Marker','o', 'MarkerSize',3) % add marker at points and specify marker's size
York University ITEC2600 By Amanda Tian

We can also add multiple functions in one plot by using “hold on” and “hold off”. See example:
>> x = 1:0.1:10
>> y1 = 2*x+2
>> plot(x,y1) % the first plot

>> hold on; % hold on to add more graphs


>> y2 = -2*x - 2;
>> plot(x,y2) % 2nd plot
>> hold off ; % no more plot, need to hold off.

We can add legend to illustrate your plot. By default the legend will be put on the right-top corner. If the location is not
appropriate, we can also specify the location.
>> legend('2*x+2', '-2*x-2') % add legend, specify the label for each function.
>> legend('2*x+2', '-2*x-2','Location','northwest') % add legend specifying location
>> legend('boxoff') % remove legend box
>> legend({'2*x+2', '-2*x-2'},'FontSize',12,'TextColor','blue') % specify legend font size and text color.
York University ITEC2600 By Amanda Tian

We can also remove legend by


>> legend off % remove legend.

Title and x-axis, y axis label can also be added.


>> x = 1:0.1:10
>> y1 = 2*x+2
>> plot(x,y1)
>> title('My Title') % add title
>> title('My Title','Color','red') % add title and specify color
>> title('My Title: \alpha^2 and X_1') % include Superscript or Subscript Character in Title
>> xlabel('x label') % add label for x axis
>> ylabel('y label') % add label for y axis

text() function allows us to add text on the plot. Usually, the first two parameters are for x-coordinate, and y-coordinate, which
specify the location. The 3rd parameter give the text to add. In the following example, we add text “(xx, yy)” to the point locate
at x = 2, y = 6.
York University ITEC2600 By Amanda Tian

>> x = 1:1:5
>> y1 = 2*x+2
>> plot(x, y1, 'Marker','*') % plot the function
>> text(2, 6,'(xx, yy)') % add text at a specified location (2, 6)

Add text to another point (3, 9), and font color is blue.
>> text(3, 9,'(xx, yy)', 'Color','blue') % specify text color

In the above two examples, the text are hard-coded. i.e. the text is a fixed string. It is not convenient if we would like to add
different text for multiple points. The following example will show how to dynamically generate the text for each point and add
them at different location. strcat() function can paste string vectors/cells. num2str() function coverts numbers to string.
>> txt = strcat('(',strsplit(num2str(x)), ',',strsplit(num2str(y1)),')') % create text for multiple points.
>> text(x,y1, txt) % add multiple text on a graph.
York University ITEC2600 By Amanda Tian

12.2 Histogram plot


Histograms are a type of bar plot for numeric data that group the data into bins. After you create a Histogram object, you can
modify aspects of the histogram by changing its property values. This is particularly useful for quickly modifying the properties
of the bins or changing the display. Usually the height of the bar indicate how many numbers fall into the corresponding range.
See example below. We create a numeric vector x which include 1000 elements, which are randomly drawn from standard
normal distribution. We then plot the histogram for the vector x. The resulted histogram has a symmetric bell shape. The peak is
around 0. That is, most elements of x are around 0, the number of the elements decreases when the elements values are far from
0. The histogram give us a brief idea how the data is distributed. In the below example
>> x = randn(1,1000); % create a sample of 1000, which follows standard normal distribution
>> histogram(x); % histogram for x

We can also specify how many vertical bar we would like to see.
>>histogram(x, 10) % specify the number of bins as 10.

When histogram() is applied to categorical data, we can design labels for each category. And specify the width of the bar by
parameter ‘BarWidth’. From the plot, we can see the height of the vertical bar represents the frequency, for example, 11 elements
are 1, 14 elements are 0, two elements are NaN.
>> A = [0 0 1 1 1 0 0 0 0 NaN NaN 1 0 0 0 1 0 1 0 1 0 0 0 1 1 1 1]; % create a vector with categorical data
>> C = categorical(A,[1 0 NaN],{'yes','no','undecided'}); % label 1 as yes, 0 as no, NaN as undecided
>> histogram(C)
>> histogram(C,'BarWidth',0.5) % specify bar width
York University ITEC2600 By Amanda Tian

12.3 Pie chart.


• Usually pie chart is used to illustrate the proportion of data.
• Pie chart shows the ‘normalized’ proportion, that is, the ration of each elements over total sum.
In the following examples, we show how to make pie chart for a vector. We create a vector x with four elements. The
corresponding pie chart has four parts. The percentage corresponding to each element. For example, the first element 1
corresponds to 1/(1+3+4+2) = 0.1 = 10%; the last elements corresponds to 2/(1+3+4+2) = 0.2 = 20%. We can also use labels to
replace the percentage on the chart.
>> x = [1, 3, 4, 2]; % create a vector with sum of 10
>> pie(x)
>> labels = {'lev 1' 'lev 2','lev 3' 'lev 4'}; % design label for the chart
>> pie(x,labels) % pie chart displaying label

The following example shows how to display both percentage and label together.
>> x = [1,2,3];
>> p = pie(x);

>> pText = findobj(p,'Type','text'); % find the text for the pie chart object p
>> percentValues = get(pText,'String'); % get the percentage
>> txt = {'Item A: ';'Item B: ';'Item C: '}; % define labels
>> combinedtxt = strcat(txt,percentValues); % combine label and percentage
>> pText(1).String = combinedtxt(1); % change the display for 1st component
>> pText(2).String = combinedtxt(2); % change the display for 2nd component
>> pText(3).String = combinedtxt(3); % change the display for 3rd component
York University ITEC2600 By Amanda Tian

12.5 Plot edit tools.


Matlab also provides flexible user-interactive tools to help us to edit the plot. We can
• Click <Save> button to choose where and which type of file you want to save your plot.
• Click <Insert> menu to add title, axis label, legend, color bar to the plot
• Click <Tools> <Rotate 3d> menu, click and drag to rotate the 3-d plot.
York University ITEC2600 By Amanda Tian

13. Data analysis.


13.1 merge two data sets with common columns.
See example below, tables T1 and T2 have common column ‘id’. Then we can merge them into one complete table.

>> id = [1;2;3;4]; % create id column


>> name = ["Peter"; "Anna"; "Lisa";"Tom"]; % create name column
>> age = [45; 44; 34; 66]; % create age column
>> T1 = table(id, name) % create table with columns id and name

T1 =
4×2 table
id name
__ _______

1 "Peter"
2 "Anna"
3 "Lisa"
4 "Tom"

>> T2 = table(id, age ) % create table with columns id and age

T2 =
4×2 table
id age
__ ___

1 45
2 44
3 34
4 66

>> d = join(T1,T2) % merge T1 and T2 by common column id

d=
4×3 table
id name age
__ _______ ___

1 "Peter" 45
2 "Anna" 44
3 "Lisa" 34
4 "Tom" 66
York University ITEC2600 By Amanda Tian

If the common columns have different column names, then we specify them by parameter: 'LeftKeys' and 'RightKeys'. See
example below:

>> T2.Properties.VariableNames{1} = 'id1' % change the column name of T2, id -> id1.

T2 =

4×2 table

id1 age
___ ___

1 45
2 44
3 34
4 66

>> % now there is no common column with same name in T1 T2.


d = join(T1,T2,'LeftKeys','id','RightKeys','id1') % merge two tables with different column names.

d=

4×3 table

id name age
__ _______ ___

1 "Peter" 45
2 "Anna" 44
3 "Lisa" 34
4 "Tom" 66

You might also like