IB352 Warwick Wk2 - Lecture2
IB352 Warwick Wk2 - Lecture2
IB352 Warwick Wk2 - Lecture2
Spring 2023
Applied Optimisation
Methods
Lecture 2
Lecturer
• Coding in Matlab
• Reading
• Getting Started with Matlab:
https://uk.mathworks.com/help/matlab/getting-started-
with-matlab.html
Integrated Development Environment
Editor
• Script file: sequences of Matlab commands
• Function file: accepts input and returns output
• Text files, extension .m
• Directory needs to be part of Matlab path: Right-click
on directory Add to path Selected folders and
sub-folder
• Run a script by either calling its name in the
command window, or clicking the Run button
Functions
• Variables used in function files only exist inside the
function, and only while the function is called
• First line:
function [y1, y2, ..., yn] = functionname(x1, x2,..., xm)
• Example
function y = average(x)
y = sum(x)/numel(x);
end
• return ends the function call at any point
• Single line functions can also be defined as
average = @(x) sum(x)/numel(x);
for Loop
• Syntax
for index = values
statements
end
• Example:
x = 0;
for i = 1 : 10
x = x + 1;
end
while Loop
• Syntax
while expression
statements
end
• The statements inside the while loop will be repeated as long
as the expression is true.
• Example:
s = 0;
i = 1;
while ((s < 10) && (i <= numel(x)))
s = s + x(i);
i = i + 1;
end
if Statements
• Syntax
if expression
statements
elseif expression
statements
else
statements
end
• Example:
if ((x >= minVal) && (x <= maxVal))
disp(’Value within specified range.’);
elseif (x > maxVal)
disp(’Value exceeds maximum value.’);
else
disp(’Value is below minimum value.’);
end
Examples