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

Unknown

This document discusses MATLAB programming concepts including variables, arrays, plotting, logical operations, conditionals like if/else, and loops like for and while. It provides examples of plotting data, fitting lines, logical operations, if/else statements, indentation, switch statements, repetition with while and for loops, formatted printing with fprintf, and stopping loops with break and continue.

Uploaded by

sufismoker31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unknown

This document discusses MATLAB programming concepts including variables, arrays, plotting, logical operations, conditionals like if/else, and loops like for and while. It provides examples of plotting data, fitting lines, logical operations, if/else statements, indentation, switch statements, repetition with while and for loops, formatted printing with fprintf, and stopping loops with break and continue.

Uploaded by

sufismoker31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

MATLAB PROGRAMMING

PART 2
ANDREW NORMAN
Last Block

• Variables – names start with a letter, can hold any type of value.
• Simple arithmetic = + - / * ^
• Setting up (initialising) arrays (vectors and matrices)
• Selecting (indexing) parts of arrays.
• Array calculations – “dot multiply” .* etc.
• Transposing with '
• Ranges – start:delta:end or linspace(start,end,points);
• Trig functions (sin, cos, sind, cosd, etc).
• save, load, diary
• Importing data – xlsread, csvread
• Getting help
Exercise – Part One

u = 100 * cos (pi/3);


v = 100 * sin (pi/3);
g = 9.81;
Ti = 2.0 * v / g;
t = linspace(0, Ti, 21);
x = u * t;
y = v * t - (g * t.^2)/2;
plot(x, y);
Graph for Part One
Exercise – Part Two

g = 9.81;
angle = linspace(0, pi/2, 21);
u = 100 * cos (angle);
v = 100 * sin (angle);
impact = 2 * v/g;
distance = u .* impact;
plot(angle, impact)
plot(angle, distance)
Graph for Part Two
Exercise – Part Two

[maxdistance, point] = max(distance)


maxdistance = 1.0194e+03
point = 11
maxangle = angle(point)
maxangle = 0.7854
Part 2

9. Plotting data
10.Review problems (plotting electricity usage and
frequency analysis)
11. MATLAB scripts
12.Logical arrays
13.Programming (if/else, loops)
14.Final project
Matlab Scripts

• What if you want to run those projectile calculations


again?
• Save the code as a script (.m file).
• Matlab has a PATH (series of folders where it looks for
scripts).
• Can run scripts from the command line.
• Useful extra command:
• x = input(<prompt>);
• Prints the prompt, waits for input, assigns a value to x.
• Prompt should be in single quotes:
• angle = input('Input an angle : ');
• To input a string (e.g. a file name):
• filename = input('File name : ', 's');
Improving the plot

• xlabel(<text>), ylabel(<text>), title(<text>), legend(<text>)


• gca – 'Current axes handle'
• Object-oriented programming
• Assign gca to a variable
• Can then work with properties of the current axes:

ax = gca;
ax.XLim = [0 1100];
ax.YLim = [0 350];
ax.XTick = 0:100:1100;
grid
grid minor
Other useful plotting commands

• hold on – keeps the current figure active, so a new line can be


plotted on it keeping the previous lines (hold off to stop).
• figure – creates a new figure (without closing the current one).
• ax.xscale = 'log' – gives a log scale:
x = 0:0.1:10;
y = exp(x);
plot(x,y);
ax = gca;
ax.YScale = 'log';

• contour – contour plot of 3-D matrix


• surf – surface (3-D) plot of 3-D matrix
Fitting a line

• polyfit(x,y,n)
• Given data in x and y, returns a polynomial of order n,
as a vector.

x = 0:10;
r = randn(size(x));
y = 3 * x + 4 + r;
plot(x,y,'r+');
ax = gca;
ax.YLim = [0 35];
Fitting a line

hold on
fit_poly = polyfit(x,y,1);
disp(fit_poly);
3.0439 3.8173
fitted = polyval(fit_poly, x);
plot(x,fitted,':');
"Programming" - logic

• Logical operators:
• == (comparison) – not to be confused with =
(assignment)
• ~= (not equal to) – some programming languages
use !=
• > < >= <=
• The two things being compared can be arrays, in
which case the result is a logical array (1=true,
0=false).
Logic

• Can't be chained
• x = 4;
•2 < x < 5
• Evaluates 2 < x to be 1 (true) and then 1 < 5 to be
1 (true)
• Returns true, but try with x = 1;
•2 < 1 < 5
• 2 < 1 is 0 (false), 0 < 5 is 1 (true)
• Need to use && (AND) or || (OR):
• (2 < x) && (x < 5)
if / else

if <condition1>
(Do something if condition1 is true)
elseif <condition2>
(Do something if condition2 is true)
elseif <condition3>
(Do something if condition3 is true)
else
(Do something if none of the previous conditions is true)
end
if / else

• elseif and else are optional – the simplest form is:

if <condition>
(Do something if condition is true)
end

• elseif is rare:

if <condition>
(Do something if condition is true)
else
(Do something if condition is false)
end
if / else

• Statements can be 'nested', one inside another:

if rem(x,2) == 0
disp('Number is even');
if rem(x,3) == 0
disp('Number is divisible by 3');
end
else
disp('Number is odd');
end
Indentation

Thou lovely and beloved, thou my love;


Whose kiss seems still the first; whose summoning eyes,
Even now, as for our love-world's new sunrise,
Shed very dawn; whose voice, attuned above
All modulation of the deep-bowered dove,
Is like a hand laid softly on the soul;
Whose hand is like a sweet voice to control
Those worn tired brows it hath the keeping of: —

What word can answer to thy word; — what gaze


To thine, which now absorbs within its sphere
My worshiping face, till I am mirrored there
Light-circled in a heaven of deep-drawn rays?
What clasp, what kiss mine inmost heart can prove,
O lovely and beloved, O my love?
(Dante Gabriel Rossetti)
Indentation

Thou lovely and beloved, thou my love;


Whose kiss seems still the first; whose summoning eyes,
Even now, as for our love-world's new sunrise,
Shed very dawn; whose voice, attuned above
All modulation of the deep-bowered dove,
Is like a hand laid softly on the soul;
Whose hand is like a sweet voice to control
Those worn tired brows it hath the keeping of: —

What word can answer to thy word; — what gaze


To thine, which now absorbs within its sphere
My worshiping face, till I am mirrored there
Light-circled in a heaven of deep-drawn rays?
What clasp, what kiss mine inmost heart can prove,
O lovely and beloved, O my love?
(Dante Gabriel Rossetti)
Back to the if statement:

if rem(x,2) == 0
disp('Number is even');
if rem(x,3) == 0
disp('Number is divisible by 3');
end
else
disp('Number is odd');
end
Back to the if statement:

if rem(x,2) == 0
disp('Number is even');
if rem(x,3) == 0
disp('Number is divisible by 3');
end
else
disp('Number is odd');
end
Not just true or false?

• Action taken depending on the value of a


variable:
if (x == 3)
disp 'Three'
elseif (x == 2)
disp 'Two'
elseif (x == 1)
disp 'One'
else
disp 'Don''t know!'
end
The switch statement

switch x
case 3
disp 'Three'
case 2
disp 'Two'
case 1
disp 'One'
otherwise
disp 'Don''t know!'
end
Repetition

• while
• Repeat while a condition is true

% Newton-Raphson method to find the square root


n = input('Input number to find the square root of : ');
root = n / 2.0;
tolerance = 0.0001;
while abs(root * root - n) > tolerance
root = (root + n/root) / 2.0;
end

fprintf('The square root of %.4f is %.4f\n', n, root);


clear
fprintf

• Formatted printing:
• fprintf(<format string>, <variable list>);
• Example:
• fprintf('The value of x is %d\n', x);
• Prints the value of x in place of %d
• Can have several format specifiers and several variables:
• fprintf('x is %d and y is %d\n', x, y);
• End with \n (newline)
• Strings in MATLAB use single quotes ' (most other programming
languages use double quotes " or allow both).
fprintf

• Formats:
• %d = print an integer (decimal)
• %x = print an integer (hexadecimal)
• %f = print a floating point number
• e.g. 31.6228 (square root of 1000)
• %e = print a floating point number in exponential
format
• e.g. 3.1623e+01
• %.3f = print a floating point number to 3 decimal
places
• e.g. 31.623

• Look up the documentation for more!


Repetition

• for
• Loops over a range

for x = 1:2:10
fprintf('x is %d\n', x);
end

x is 1
x is 3
x is 5
x is 7
x is 9
For loop - example

% Coordinates of a peak
peakx = 38;
peaky = 72;

% Set up a large 2-D array for values


A = zeros(100,100);

% Calculate the function at each point in the array


for x = 1:100
for y = 1:100
distance = sqrt((x - peakx)^2 + (y - peaky)^2);
A(x,y) = sin(distance) / distance;
end
end

surf(A);
Output
Stopping a loop

• break
• Stops the loop and ends it
• continue
• Stops the loop and moves to the next iteration (cycle)

• Example code on Blackboard or documentation.


• break and continue should be used sparingly.

You might also like