0% found this document useful (0 votes)
15 views21 pages

143 MATLABFinal Solutions

This document provides an overview and examples of using MATLAB. It covers defining variables, arrays and matrices, plotting data, importing data, if/else and loop statements, defining functions, curve fitting, interpolation, and numerical calculus techniques. Key aspects covered include basic MATLAB layout, accessing values in arrays and matrices, plotting multiple lines, importing data from files, writing if/else and for/while loops, defining inline and regular functions, using polyfit for curve fitting and interp1/pchip for interpolation, and calculating derivatives numerically and with the diff function.

Uploaded by

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

143 MATLABFinal Solutions

This document provides an overview and examples of using MATLAB. It covers defining variables, arrays and matrices, plotting data, importing data, if/else and loop statements, defining functions, curve fitting, interpolation, and numerical calculus techniques. Key aspects covered include basic MATLAB layout, accessing values in arrays and matrices, plotting multiple lines, importing data from files, writing if/else and for/while loops, defining inline and regular functions, using polyfit for curve fitting and interp1/pchip for interpolation, and calculating derivatives numerically and with the diff function.

Uploaded by

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

APSC 143 Matlab

Workbook Solutions

Written by Carson Cook


APSC 143 Matlab Workbook Solutions

Tour of MATLAB
When you open MATLAB, you will see something like this.

A
C

A) Current Folder. When you open MATLAB, change this folder to the location you have saved any
scripts or relevant files.
B) Command Window. Use this to enter commands and immediately see the output below. This
is also where error messages would appear
C) Editor window. If this window is not visible, either open a script or click new in the top left
corner of the window. Scripts are where you write multiple lines of code and then run the
whole block of code at one time to execute the series of commands. You can save scripts and
come back to them later. You can’t re-execute commands entered in the command window the
same way
D) Workspace. Once you have declared variables, they will appear here.
E) Run Button. Click this button to run your script.

1 of 20
APSC 143 Matlab Workbook Solutions

Defining Variables
In Matlab, unlike C, the type of a variable doesn’t have to be defined.

Variable Type Definition Example


Number (double, int, etc.) Single number X = 45
String (in C, a char array) A word. Enclose in quotes. Name = “Harry Potter”
Y = [2, 3, 4, 5, 6]
Array Many numbers Or
Y = [2; 3; 4; 5; 6]

Arrays and Indexing


Create an array of integers from 1 to 6:

Using the colon syntax (shown to create the array stored in B), you can omit the step size (the middle
number) if you increment each element by 1.

If the number of elements (the right-most number) is not passed through the linspace() function, it
creates an array of 100 elements automatically.

Accessing a value in an array is the same as C, except you use round brackets and indexing starts at 1:
A(1) //equal to 1!

Matrices
Here is an example of how to define a matrix in MATLAB:

To access a value from a matrix, we identify the row and column number. For example, in the matrix M,
to access the value 18, we would type M(4,3).

2 of 20
APSC 143 Matlab Workbook Solutions

Multiplying arrays
To multiply/divide/exponentiate each element in a matrix by another element in another matrix, ‘.’
must be added before the operator.

Plotting
To plot data, we create a figure using the figure command and then use the plot function. The basic
syntax is

figure
plot(x,y)

If we want to plot more than one line, there are two ways to do this. The first is by specifying more than
one line in the plot function like this:

figure
plot(x,y,x,z)

The second is to use the hold function. This tells MATLAB not to overwrite the first plot with the second.

hold on
plot(x,z)

3 of 20
APSC 143 Matlab Workbook Solutions

Controlling Plot Properties


Create a plot with two lines:

This is the graph generated by this code:

4 of 20
APSC 143 Matlab Workbook Solutions

Importing Data
Import Data function
The import wizard is easy to use when you’re learning MATLAB, but it is much more efficient to import
your data in your script so you do not have to redo it whenever you run your code again.

This is the syntax:

Read Microsoft Excel File


xlsread() is another function that can be used to import data from excel.

If Else Statements
Create an if-chain that tells us if ‘val’ is bigger than 3

//Equivalent in C:
if (val>3)
{
printf(“val is more than 3”);
}
else if (val==3)
{
printf(“The value is 3”);
}
else
{
printf(“val is less than 3”);
}

5 of 20
APSC 143 Matlab Workbook Solutions

For Loops
Create a for loop that will run 10 times:

//Equivalent in C:
int Value=1;
for (int i=1; i<=10; i++)
{
Value+=i;
}

While Loops
Create a while loop that will run 10 times:

//Equivalent in C:
int Number=1;
while (Number<10)
{
Number=Number+Number;
}

Functions
Defining functions
Here is the basic syntax for defining a function.

6 of 20
APSC 143 Matlab Workbook Solutions

Inline functions
Simple mathematical functions can be defined inline without creating a whole .m file for them.

Curve Fitting and Interpolation


Polyfit is a function used to fit a polynomial function to a set of data. The function polyval can be used
to evaluate the polynomial function.

120

100

80

60

40

20

-20
-10 -8 -6 -4 -2 0 2 4 6 8

Polyfit creates a line of best fit between data points but does not necessarily pass through every data
point. To connect data points using a line that passes through all points we can use two other functions.

7 of 20
APSC 143 Matlab Workbook Solutions

Interpolation
To create a linear interpolation between each point, use the function interp1.

120

100

80

60

40

20

-20
-10 -8 -6 -4 -2 0 2 4 6 8

Smooth Interpolation
Another method of interpolating is using the pchip function to create a smooth interpolation between
points.

160

140

120

100

80

60

40

20

-20
-10 -8 -6 -4 -2 0 2 4 6 8 10

8 of 20
APSC 143 Matlab Workbook Solutions

Numerical Calculus
Sometimes we want the derivative or integral of our data. There are many ways to do this.

Derivatives
We can either calculate a derivative using the definition of a derivative or by using the diff() function.

Recall from calculus that this is the definition of a derivative:

𝑓(𝑎 + ℎ) − 𝑓(𝑎)
𝑓′ = lim
ℎ→0 ℎ
Here is an example of using the definition of a derivative to calculate a derivative:

100

80

60

40

20

-20

f(x)
df/dx
-40
-10 -8 -6 -4 -2 0 2 4 6 8 10

We can also use the diff function to calculate the derivative. The diff function returns the difference
between consecutive values of an array.

A good way to think of this method is that we are computing rise over run between each point.
Remember your dfdx array will be one shorter than your original y and x arrays. If you must plot the
derivative, remove the first element from your x array to make the arrays the same length.

9 of 20
APSC 143 Matlab Workbook Solutions

Integrals
Using the same anonymous function as we used for the derivative, we can calculate the area under the
curve using the integral function.

We can also use the cumtrapz function:

Plot Formatting Values


Line Style Description

- Solid line (default)

-- Dashed line

: Dotted line

-. Dash-dot line

Marker Description

o Circle

+ Plus sign

* Asterisk

. Point

x Cross

s Square

d Diamond

^ Upward-pointing triangle

v Downward-pointing triangle

> Right-pointing triangle

< Left-pointing triangle

p Pentagram

h Hexagram

10 of 20
APSC 143 Matlab Workbook Solutions

Color Description

y yellow

m magenta

c cyan

r red

g green

b blue

w white

k black

Arduino and MATLAB


Arduino boards are microcontrollers that allow users to access and control different electronic
components. This is accomplished by writing programs for the Arduino to specify what it should “read
in” for values and how the values should effect the output of the program or the electronic components.

MATLAB needs an Arduino object variable in order to use any of the Arduino functions. The following
command should be run first:

Any Arduino function must reference the object variable (in the example above, it’s called “ard”).

The 2 types of input/output pins:

1. Analog: Takes on any value in a range (ex. Any voltage from 0 – 5V). Pins A0 – A5
2. Digital: Takes on a HIGH or LOW value (ex. 5V or 0V). Pins D0 – D13

Input pins can be either analog or digital pins, whereas output pins are only digital pins.

To determine whether a pin should be set up as an input pin or an output pin, think about what the pin
is connected to – what is the component doing/used for? For example, if a pin is connected to a
photoresistor that senses the amount of light hitting the sensor, the pin should be configured as an
input pin because it is taking in/reading values from the sensor. If a pin is connected to an LED that
needs to be turned on or off based on the readings from the photoresistor, it should be configured as an
output pin. The LED is completing a task/action based off of another sensor’s value.

To configure pins, the commands are:

11 of 20
APSC 143 Matlab Workbook Solutions

To read from a pin (used for input pins):

To send a voltage to a pin (used for output pins):

Questions
1. Write a Program
Bob fires a cannon horizontally off a hill. The following data is the height of the cannon ball above the
ground at different times. The sensor used to measure the height of the cannon above the ground is
buggy. Write a function that removes any data point that is greater than the previous data point. Fit a
second order polynomial to this data. Plot the cleaned data as data points and the fitted line on the
same graph and add a legend, axis labels and a title. Calculate the derivative of the data (the speed of
the ball in the y direction) using the data from the line of best fit. On a second plot, plot the derivative as
points. Publish the script as a pdf.

Data:
Time 0 50 750 800 825 1000 1250 1500 1700 1900 2000 2250 2500 2600 2750 3000 3100
(ms)
Height 10 9.99 9.43 9.36 9.5 9.0 8.44 7.75 7.11 6.39 6.0 4.94 3.75 5.0 2.44 1.0 0.39
(m)

Extensions:

• Calculate the derivative of the data by creating an inline function using the coefficients from the
polynomial fit
• Find the time when the cannon hits the ground using the roots function
• Instead of using the original time data to generate the fitted data, create a finer sampled time
array
• Calculate the R2 of the fit

12 of 20
APSC 143 Matlab Workbook Solutions

%Practice Test Script

%time data converted from ms to s


time=[0,50,750,800,825,1000,1250,1500,1700,1900,2000,2250,2500,2600,2750,3000,3100]*1e-3;

%height in m
height=[10,9.99,9.43,9.36,9.5,9.0,8.44,7.75,7.11,6.39,6.0,4.94,3.75,5.0,2.44,1.0,0.39];

[heightClean,timeClean]=cleanUp(height,time); %call the function to


cleanup the height Data

%fit a second order polynomial to the data

P=polyfit(timeClean,heightClean,2);

heightFit=polyval(P,time);

%plot the cleaned data as data points and line of best fit

figure
hold on
plot(timeClean,heightClean, 'x');
plot(time,heightFit);

xlabel('time (s)');
ylabel('height (m)');

title('Height vs. time' );


legend('Data','Line of Best Fit' );

%Calculate Derivative

dhdt=diff(heightFit)./diff(time);

figure
plot(time(2:end),dhdt, 'x');

xlabel('time (s)');
ylabel('velocity in y direction (m/s)' )
title('velocity vs. time' );

Height vs. time velocity vs. time


10 0
Data
Line of Best Fit
9
-1
8

7 -2
velocity in y direction (m/s)

6
-3
height (m)

-4
4

3 -5

2
1 -6
1

0 -7
0 0.5 1 1.5 2 2.5 3 3.5 0 0.5 1 1.5 2 2.5 3 3.5
time (s) time (s)

13 of 20
APSC 143 Matlab Workbook Solutions

function [cleanedData,cleanX] = cleanUp(Data,x)


%This function removes all values of 1D array Data that are greater
than
%the previous value in the array. This is just one way to do this,
there
%is not only one solution.

n=length(Data); %variable for the length of the data


remove=[];%initialize an array to store indices of values to delete

for i=2:n
if Data(i)>Data(i-1)
remove=[remove,i];
end

end

cleanedData=Data; %cleanedData is equal to data


cleanedData(remove)=[]; %remove points that are wrong

cleanX=x;
cleanX(remove)=[]; %remove the same values from the x array

end

Not enough input arguments.

Error in cleanUp (line 6)


n=length(Data); %variable for the length of the data

Published with MATLAB® R2016b

2. Plotting Function Values


Let us plot projectile trajectories using equations for ideal projectile motion:

where y(t) is the vertical distance and x(t) is the horizontal distance traveled by the projectile in metres,
g is the acceleration due to Earth’s gravity (9.8 m/s2) and t is time in seconds. Let us assume that the
initial velocity of the projectile is 50.75 m/s and the projectile’s launching angle is 5π/12 radians. The
initial vertical and horizontal positions of the projectile are 0 m. Let us now plot y vs. t and x vs. t in two
separate graphs with the vector:

t = 0:0.1:10 representing time in seconds. Give appropriate titles to the graphs and label the axes. Make
sure the grid lines are visible. 1

14 of 20
APSC 143 Matlab Workbook Solutions

t = 0 : 0.1 : 10;
g = 9.8;
v0 = 50.75;
theta0 = 5*pi/12;
y0 = 0;
x0 = 0;
y = y0 - 0.5 * g * t.^2 + v0*sin(theta0).*t;
x = x0 + v0*cos(theta0).*t;

figure 1;
plot(t,x);
title(’x(t) vs. t’);
xlabel(’Time (s)’);
ylabel(’Horizontal Distance (m)’);
grid on;

figure 2;
plot(t,y);
title(’y(t) vs. t’);
xlabel(’Time (s)’);
ylabel(’Altitude (m)’);
grid on;

15 of 20
APSC 143 Matlab Workbook Solutions

3. Working with arrays


You are given a text file called ballSamples that contains the following information:

a. The first column contains the ball number starting at 1


b. The second column contains the masses of the ball
c. The third column contains the colour of the ball, with 0 = red, 1 = blue, and 2 = yellow

Write a script that reads the information from the text file and:

I. Groups each ball by colour into a 2D array that contains the ball number in the first row
and the mass in the second row
II. Displays the average mass of each group
III. Finds the ball number of the heaviest red ball and the lightest blue ball
IV. Prints out which group has the largest number of balls, and the number of balls in that
specific group

Assume that there is some sort of header for each column in the first line of the file, and that each
column is separated by spaces.

Read from the file


data = dlmread('ballSamples.txt',' ',1,0); %start reading from the next row down to avoid reading
characters
number = data(:,1);
mass = data(:,2);
colour = data(:,3);

sort the balls


red = zeros(2,length(data));
rcount = 1;
blue = zeros(2,length(data));
bcount = 1;
yellow = zeros(2,length(data));
ycount = 1;
for i = 1:length(number)
if colour(i) == 0
red(1,rcount) = number(i,1);
red(2,rcount) = mass(i,1);
rcount = rcount+1;
elseif colour(i) == 1
blue(1,bcount) = number(i,1);
blue(2,bcount) = mass(i,1);
bcount = bcount+1;
else
yellow(1,ycount) = number(i,1);
yellow(2,ycount) = mass(i,1);
ycount = ycount+1;
end
end
red = red(:,rcount-1);

16 of 20
APSC 143 Matlab Workbook Solutions

blue = blue(:,bcount-1);
yellow = yellow(:,ycount-1);
ravg = sum(red(2,:))/length(red);
bavg = sum(blue(2,:))/length(blue);
yavg = sum(yellow(2,:))/length(yellow);
fprintf('average of red masses: %f0.2 | average of blue masses: %f0.2 | average of yellow masses:
%f0.2',ravg,bavg,yavg);

Find the heaviest red ball and lightest blue ball


max = 0;
max_i = 1;
min = 1000;
min_i = 1;
for i = 1:rcount-1
if red(2,i)>max
max = red(2,i);
max_i = i;
end
end

for i = 1:bcount-1
if blue(2,i)<min
min = blue(2,i);
min_i = i;
end
end
fprintf('The heaviest red ball is number %d, and it has a mass of %f. The lightest blue ball is
%d, and it has a mass of %f.',max_i,max,min_i,min);

Find the biggest group


[val,idx] = max([rcount-1,bcount-1,ycount-1]);
if idx == 1
fprintf('The largest group is the red group. It has %d balls', val);
elseif idx ==2
fprintf('The largest group is the blue group. It has %d balls', val);
else
fprintf('The largest group is the yellow group. It has %d balls', val);

4. Arduino and MATLAB


You have been given an Arduino board that has been set up to take readings from 5 different push
buttons. The user should be able to use the push buttons to plot data onto a graph that appears in
MATLAB. The following sequence of buttons should be used:

a. If button 1 is pressed, the x component is incremented


b. If button 2 is pressed, the x component is decremented
c. If button 3 is pressed, the y component is incremented
d. If button 4 is pressed, the y component is decremented

17 of 20
APSC 143 Matlab Workbook Solutions

e. If button 5 is pressed, the current x and y components are saved to be plotted


f. If both button 1 and 3 are pressed, a plot of the current data should be displayed in red
circles.
g. If both buttons 2 and 4 are pressed, no additional data is provided and the program
ends. A plot of the finalized data should appear in blue points.

The following pin connections are provided:

I. Button 1 = pin 3
II. Button 2 = pin 4
III. Button 3 = pin 5
IV. Button 4 = pin 6
V. Button 5 = pin 7

And the following command has already been run:

ard = arduino();

Write a script that will run the program described.

Establish Pin Connections


configurePin(ard,'D3','DigitalInput'); % button 1
configurePin(ard,'D4','DigitalInput'); % button 2
configurePin(ard,'D5','DigitalInput'); % button 3
configurePin(ard,'D6','DigitalInput'); % button 4
configurePin(ard,'D7','DigitalInput'); % button 5

Main program
Create array to hold x and y components

x = zeros(1,1000);
y = zeros(1,1000);
i = 1;
while true
% Get the readings from the push buttons
button1 = readDigitalPin(ard,'D3');
button2 = readDigitalPin(ard,'D4');
button3 = readDigitalPin(ard,'D5');
button4 = readDigitalPin(ard,'D6');
button5 = readDigitalPin(ard,'D7');

if button1 == 1
if button3 == 1
plot(x,y,'ro');
end
x(i) = x(i)+1;
end
if button2 == 1
if button4 == 1
break; % both button 2 and button 4 are pressed, we exit the program

18 of 20
APSC 143 Matlab Workbook Solutions

end
x(i)= x(i)-1;
end
if button3 == 1
y(i) = y(i)+1;
end
if button4 == 1
y(i) = y(i) -1;
end
if button5 == 1
i = i+1;
end
end
plot(x,y,'b.');

19 of 20
APSC 143 Matlab Workbook Solutions

Other Useful Functions


1. L = length(a)
length() returns the largest array dimension of matrix “a”. For example if a was a 2x3 matrix,
length(a) returns 3. If the matrix is just an array (i.e. one row or one column) it returns the
length of the array
Useful for: for loop indexing – if you don’t know the length of your array, use length(a) as the
last index number

2. S = sum(a)
Sum() finds the sum of all of the elements in an array

3. [max_val,max_idx] = max(a)
Max() finds the largest element of the array and the index at which it is found. If only the
maximum value is needed, max_idx can be omitted.

To find the minimum value of an array, use min(a)

20 of 20

You might also like