0% found this document useful (0 votes)
48 views

Week : For For If End End End End Function

This document provides coding tips and lessons on using matrices in MATLAB based on students' exercise code. It discusses proper indentation, using end keywords, avoiding over-commenting or overloading built-in functions, and how to write help text. It also demonstrates how to create matrices using functions like ones, zeros, eye, and rand, and how to transpose and concatenate matrices. Students are encouraged to write their own code and avoid plagiarism.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Week : For For If End End End End Function

This document provides coding tips and lessons on using matrices in MATLAB based on students' exercise code. It discusses proper indentation, using end keywords, avoiding over-commenting or overloading built-in functions, and how to write help text. It also demonstrates how to create matrices using functions like ones, zeros, eye, and rand, and how to transpose and concatenate matrices. Students are encouraged to write their own code and avoid plagiarism.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Introduction

Notes on the Exercises

Our plagiarism check found students who had very similar code:
Programming in MATLAB

Gertjan van den Burg


Week

Y
Make sure to write your code yourself!
/

Introduction Introduction
Recap Last Week Todays Topics

What we will do today:


Last week we learned:
I Present some code tips based on your programs for the
I Basics of the MATLAB language (variables, conditionals,
exercises
loops, vectors, and functions)
I Learn how to use matrices in MATLAB
I Basic types in MATLAB
I Learn about plotting in MATLAB
I How to use the MATLAB debugger
I Learn about le I/O in MATLAB
I How unit testing can help to avoid bugs
I Learn about memory and how to use it efciently in
MATLAB
Are there any questions about the material from last week?
I Learn how to prole and speed up our code

/ /

Coding Tips Coding Tips


Indentation Missing end keyword

Indentation matters for code readability


Using end to close a function helps readability
for i=1:n
for j=1:n function [c] = first_function(a)
if i > j c = a + increment(a)
a = a + 1
end function [a] = increment(a)
end a = a + 1;
end

function [c] = first_function(a)


for i=1:n c = a + increment(a)
for j=1:n end
if i > j
a = a + 1 function [a] = increment(a)
end a = a + 1;
end end
end

/ 6/
Coding Tips Coding Tips
Over-commenting Overloading builtin

There is a point where too many comments reduce the Spotted this type of code a few times in Sum Divisors:
readability of your code: sum = 0;
for i=1:n
function [S] = my_sum(x) sum = sum + i;
% MY_SUM Sum numbers in a vector end
% [S] = my_sum(x) sums all elements in x

S = 0; % Set the starting value to zero


But this can become problematic when you need to use sum as a
for i=1:numel(x) % iterate over 1 to length of x function:
S = S + x(i) % add the i th element to S
end % close the for loop sum = 0;
end % close the function for i=1:n
sum = sum + sum(1:i);
Try to nd a balance. end

/ 8/

Coding Tips Coding Tips


Empty if statements Writing Help text

Autolab checks for two things in your help text:


I Function name in capital letters
These are equivalent and valid MATLAB:
I Function signature included
if k > 0 if k > 0
This is done to encourage you to write help text in a specic
res = res + k; res = res + k;
else end format used for MATLAB documentation.
end
For example, the builtin function numel:
As are these:
function [N] = numel(A)
if k > 0 if k <= 0 % NUMEL Number of elements in an array or subscripted
else res = res + k; % array expression.
res = res + k; end % [N] = numel(A) returns the number of elements, N,
end % in array A, equivalent to PROD(SIZE(A)).
%
% See also size, prod, subsref.
N = prod(size(A));

/ /

Matrix Algebra Matrix Algebra


Creating Matrices (/) Creating Matrices (/)

Concatenation can be used to combine data into a vector or a


The easiest way to create a new matrix is with one of the
matrix:
following functions:
>> a = [1 2 3];
>> A = ones(2, 3)
>> b = [4 5 6];
1 1 1
>> c = [a b]
1 1 1
1 2 3 4 5 6
>> A = zeros(2, 4)
0 0 0 0
0 0 0 0 Or to combine vectors into a matrix:
>> A = eye(2)
1 0 >> a = [1 2 3];
0 1 >> b = [4 5 6];
>> A = rand(2, 3) >> c = [a; b]
0.79685 0.45532 0.87406 1 2 3
0.63808 0.80119 0.66488 4 5 6

Note the use of the semicolon (;) to get vertical concatenation

/ /
Matrix Algebra Matrix Algebra
Using Matrices: Transpose Intermezzo: numel, length & size

Transposing a matrix in MATLAB can be done using the There is a difference between numel, length, and size:
apostrophe:
>> X = [1 2 3; 4 5 6]
>> Y = X';
>> X = [1 2 3; 4 5 6]
>> size(X)
1 2 3
2 3
4 5 6
>> size(Y)
>> Y = X'
3 2
1 4
>> length(X)
2 5
3
3 6
>> length(Y)
3
Get matrix dimensions using size: >> numel(X)
6
>> size(X) >> numel(Y)
ans = 2 3 6
>> size(Y) >> size(X, 1)
ans = 3 2 2

/ /

Matrix Algebra Matrix Algebra


Using Matrices: Arithmetic Using Matrices: Indexing (/)

Matrix products only work if the inner dimensions agree:


Accessing matrix elements is similar to how its done for vectors:
C = A B
np nm mp
>> A = rand(2, 3)
This holds also in MATLAB: 0.963101 0.538288 0.067098
0.035767 0.554350 0.865936
>> A = rand(2, 3); >> A(1, 1)
>> B = rand(3, 4); 0.963101
>> C = A * B >> A(2, 3)
1.50337 0.67041 0.90480 1.71883 0.865936
0.53347 0.22982 0.60756 1.05374 >> A(2, 2) = 5
0.963101 0.538288 0.067098
>> C = B * A 0.035767 5.000000 0.865936
Error using _*_
Inner matrix dimensions must agree.

/ 6/

Matrix Algebra Matrix Algebra


Using Matrices: Indexing (/) Using Matrices: Indexing (/)

Matrices can be indexed using a range too: Some more matrix indexing:

>> A = rand(3, 3) >> A = rand(2, 3)


0.33766 0.45736 0.98737 0.963101 0.538288 0.067098
0.52763 0.70984 0.86388 0.035767 0.554350 0.865936
0.16245 0.62284 0.62419 >> A(:, 1)
>> A(1, 2:3) 0.963101
0.45736 0.98737 0.035767
>> A(2:3, 1:2) >> A(2, :)
0.52763 0.70984 0.035767 0.554350 0.865936
0.16245 0.62284
Indexing with a logical matrix yields a column vector:
Or, they can be indexed using a single number:
>> A(A > 0.5)
>> A(6) 0.963101
0.62284 0.538288
0.554350
0.865936
In this case, MATLAB will count column-wise.
/ 8/
Matrix Algebra Matrix Algebra
Using Matrices: Indexing (/) Intermezzo: Short-circuiting

Logical vectors can be combined with a single | or &: Why is there even a difference between |, ||, &, and &&?
>> x = 5:10
5 6 7 8 9 10 Here, both sides are evaluated, and then & is performed:

>> x < 7 x = 0;
1 1 0 0 0 0 if (x ~= 0) & (5/x < 1.0)
a = a + x;
>> x > 8 end
0 0 0 0 1 1
Whereas here, evaluation stops after the rst comparison:
>> x < 7 | x > 8 % use | (OR) to combine
1 1 0 0 1 1 x = 0;
if (x ~= 0) && (5/x < 1.0)
>> x(x < 7 | x > 8) a = a + x;
5 6 9 10 end

>> x(x > 7 & x < 10) % use & (AND) to combine Therefore, we use || and && in if statements, and | and & with
8 9 indexing.
/ /

Matrix Algebra Matrix Algebra


Solving Linear Systems Ordinary Least Squares

MATLAB is a great tool for solving systems of the form:


Recall that Ordinary Least Squares (OLS) solves,
Ax = b
Xb=y
Take for instance the following system of equations:
From the rst year, we know that the OLS estimator is given by:
x + x + x =
x + x + x = 6
b = (XX) Xy
x + x + x =
A direct translation of this to MATLAB code would be
In MATLAB:
>> b = inv(X'*X)*X'*y;
>> A = [2 1 3; 1 1 1; 1 3 2];
>> b = [10; 6; 13]; MATLAB does OLS when dividing by a non-square matrix:
>> x = A \ b
2.0 >> b = X \ y;
3.0
1.0 (see: help mldivide)
/ /

Plotting Plotting
Demo: Plotting Demo: Plotting: Intro

Our rst plot:

>> y = 1:10;
Plotting functionality in MATLAB is great! >> plot(y)

Lets do a demo! Our second plot:

>> x = 5:5;
>> y = x .^ 2
Note: The demo le will be on Blackboard. The following slides >> plot(x, y)
are just for reference.
Closing all plots:

>> close

/ /
Plotting Plotting
Demo: Plotting: Options Demo: Plotting: Labelling

Plot options (see help plot for more)


Labelling and axis setting
>> plot(x, y, 'r')
>> plot(x, y, ' r*')
>> temperature = 17.88 + 5*rand(1, 31);
>> days = 1:31;
Advanced plot options: >> plot(days, temperature);
>> xlabel('Days');
>> plot(x, y, 'LineWidth', 3, ... >> ylabel('Temperature');
'MarkerEdgeColor', 'k', ... >> title('Temperature in Rotterdam, August 2015');
'MarkerSize', 10) >> axis([1, 31, min(temperature), max(temperature)]);

Note: You can use ellipsis (...) to continue a command on the


next line. This can help keep your code readable!

/ 6/

Plotting Plotting
Demo: Plotting: Combining plots -D Plotting: Intro

Combining plots can be done in one plot as follows:


-D plotting can be used when
>> plot(1:10, 'k. '); you want to visualize a function
>> hold on;
>> plot(10: 1:1, 'r *'); or data which is dependent on
>> hold off; two variables, i.e. 200

150

Or using subplots: z = f(x, y) 100

50

>> subplot(1, 2, 1); For instance 0


>> plot(1:10, 'k. '); 10

>> subplot(1, 2, 2); z = f(x, y) = x + y


5 10

0 5

>> plot(10: 1:1, 'r *'); -5


-5
0

-10 -10

We need to evaluate f(x, y) at


Or, if you want a new gure window to plot in, use:
every combination of x and y.
>> figure

/ 8/

Plotting Plotting
-D Plotting: Meshgrid -D Plotting: Meshgrid

Using this X and Y from meshgrid, we can calculate our -D


The function meshgrid creates this grid for -D plotting function using elementwise multiplication:
>> x = 2:2; >> x = 2:2;
>> y = 1:1; >> y = 1:1;
>> [X, Y] = meshgrid(x, y) >> [X, Y] = meshgrid(x, y);
X = >> Z = X.^2 + Y.^2
2 1 0 1 2 Z =
2 1 0 1 2 5 2 1 2 5
2 1 0 1 2 4 1 0 1 4
Y = 5 2 1 2 5
1 1 1 1 1
0 0 0 0 0
Finally, create the plot using either surf or mesh:
1 1 1 1 1
>> surf(X, Y, Z)

/ /
Plotting File I/O
Utilities The Workspace

A nal useful plotting function is the hist function, for creating


histograms:
In some cases, it can be useful to save your current variables for
>> x = randn(1, 1e6) later use:
>> hist(x, 100)
>> save('myworkspace.mat')
40000

or:
30000 >> save('myworkspace.mat', 'x', 'y')

At a later date, you can reload your workspace using


20000

>> load('myworkspace.mat')
10000

Be careful: Existing variables will be overwritten!

0
-6 -4 -2 0 2 4 6

/ /

File I/O File I/O


CSV Files Formatting text output (/)

Real-life data is often supplied as CSV les, which look like this:
Writing data to screen can be done using fprintf
25.133,3.1416,18.85
9.4248,15.708,21.991 >> fprintf('Bananas contain a lot of potassium.')
12.566,28.274,6.2832 Bananas contain a lot of potassium.>>

We can load this data into a matrix using Notice that there is no linebreak after the sentence, we have to
add this manually:
>> A = csvread('mydata.csv');
>> fprintf('Bananas contain a lot of potassium.\n')
Writing data to CSV les is not done using csvwrite but through: Bananas contain a lot of potassium.
>>
>> dlmwrite('myoutput.csv', A, 'precision', 16);

This saves the data with more precision than csvwrite.

/ /

File I/O File I/O


Formatting text output (/) Writing to text les

The function fprintf can also format numbers or strings into Writing formatted text to a le requires opening the le in
text: MATLAB rst:

>> fprintf('%i bananas have %.2f grams of %s.\n', ... >> fileID = fopen('myoutputfile.txt', 'w');
3, 1.266, 'potassium')
3 bananas contain 1.27 grams of potassium. Then, we can write to the le by specifying the le ID in fprintf:
>>
>> fprintf(fileID, 'Bananas!\n');
Here, we have format strings: >> fprintf(fileID, ...
'%i banana contains %.3f grams of potassium.\n', ...
I %i prints an integer 1, 0.422);
I %.2f prints a oating point number to decimal places
I %s prints a string When were done writing to the le, we close it again:

>> fclose(fileID);
Format strings are available in many other languages, including
Java. Note: Not closing the le can lead to weird bugs!

/ 6/
Memory Usage Memory Usage
Theory Practice

When you store a vector in MATLAB:

>> x = 1:3;
Memory in your computer (RAM) can be seen as a list of boxes:
itll be in adjacent boxes somewhere:
... ...
... ...

A computer program asks the Operating System (OS) for some


boxes, every time you need to store some data. When you concatenate you create a new vector:

>> x = [x 4];
Programs that constantly have to ask the OS for more boxes, will
be slow. Which means a reallocation occurs:
... ...

Reallocations can slow down your code signicantly!


/ 8/

Proling Proling
Demo: Timing Code Sections Demo: Proling

Timing pieces of code can be done using tic and toc:

tic; If you want to nd out where your code is slow, use the proler:
x = 1:1e5;
y = []; >> profile on
for xi=x >> my_slow_function();
y = [y xi^2]; >> profile off
6 end >> profile viewer
elapsed = toc

Compare this with:

tic;
x = 1:1e5;
First make it work, then make it fast.
y = x.^2;
elapsed = toc

/ /

You might also like