Exercises PDF

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

Matlab Exercises

Part 1
version 5, EJP, 2013

1. Start matlab. 5. Enter the following

2. Enter the following a = [1 2 3]


b = [4 5 6]
1+2 Z = a + i*b
x=1+2
x = 1 + 2; i here is the square root of -1.
y = x^2 + 2*x + 8 You can use j instead if that is what
you are use to.
3. Enter the following
6. Display the real and imaginary
format long e parts of Z and the conjugate of Z.
pi
7. Display the magnitude and angle
You can use the arrow keys and the of Z.
delete key to recall and edit previous
commands. Press the up arrow key 8. Try the following.
twice to recall the format command
and delete the "e" and press enter. Z'
Then display pi again. Repeat with the Z.'
following formats.

format short e
format short

4. Enter the following

a = pi/6
sin(a)^2 + cos(a)^2
exp(2*log(3) + 3*log(2))

1
9. Enter the two matrices 12. It is just as easy to solve a
hundred simultaneous equations in a
1 2 5 6 hundred variables. First create a 100
A  B  by 100 matrix of random numbers.
3 4 7 8 
A1 = rand(100);
10. Try the following and ensure
you can follow what is happening. If you forget to put in the semicolon,
10,000 numbers will be printed out.
A+5
A+B Next create a column vector with 100
A-B numbers
A*B
A^2 b = (1:100)'
A'
Now solve
11. Solve the simultaneous equation
on page 15 of the notes. A should x = A1 \ b
already be present from exercise 10.
Check that the solution is correct.
b = [ 5 ; 11 ]
x=A\b A1 * x
Now check that x is the correct
solution.

A*x

2
Part 2
1. You should have the two matrices
4. Plot the polynomial 4 x 3 −3 x
1 2 5 6 using the function polyval. First find
A  B  out how to use polyval using the help.
3 4 7 8 
doc polyval
from exercise 10 in part 1.
If not, then enter them again.
p = [4 0 -3 0]
y1 = polyval(p,x);
2. Now try the following array
operations.
hold on
plot(x,y1,'g')
A .* B
A ./ B
5. There are many functions that
A .^ B
handle polynomials. Look them up in
sin(A * pi/6)
the help. Enter doc polyval again,
D = A.^2
then click on polynomials on the path
sqrt(D)
at the top of the page.

What does the function roots do?


Clear the workspace of all variables.
clear
6. Plot the roots of the polynomial
onto the graph.
3. Plot the polynomial 2 x 3− x
r = roots(p)
x = linspace(-1,1,100); ry = zeros(3,1)
y = 2*x.^3 -x;
The plot should still be held from
What happens if you don't include exercise 4.
the dot ?
plot(r,ry,'rx')
plot(x,y)
Clear the figure
Don't close the figure containing the clf
plot.

3
7. Enter the following. All variables should have been saved
to matlab.mat . If you can't see this in
a = 2: 0.5 : 4 the "Current Folder" window, right
click in the window and select refresh.
a(2)
a([2 4]) The workspace window should be
a(2:4) empty. Double click on matlab.mat to
a(2:end) restore all your variables.

11. Produce and a script called graph.


8. Enter the following
edit graph
w = (1:5)' * (5:10)
In graph enter
This produce a 5 by 6 matrix that we
can use in the next exercise. x = linspace(-2*pi,2*pi,100);
y = sin(x);
Set the third element on the second plot(x,y)
row of w to 100. grid

9. Enter the following Save by clicking on the icon


and run by entering
w(2:4,2:4)
w(2,:) graph
w(:,5)
w([1 5],[2,4]) in the command window.
w(:)
w(:) = 1:30
12. Add the following at the end of the
10. By now you should have a nice script created above.
collection of variables. Try

who hold on
whos y1 = mysin(x);
plot(x,y1,'r:')
You will also be able to see your axis( [-2*pi,2*pi,-2,2] )
variables in the workspace window.
Click on the "Save and Run" icon
Enter the following in the command
window.

save
clear

4
13. You should have a file called mysqrt.m. Edit this file

edit mysqrt

function x=mysqrt(A)

% My square root function.


%
% x = mysqrt(A)
%
% x is the square root of A.

x=1; %First guess


err=1; %Set error to something to get started

while(err>0.0001)
x = myfunction(A,x); % call to local function below
err = abs(A -x.^2); % calculate the error
end

function y = myfunction(A,x)
% Local function to calculate the
% Newton Raphson Iteration equation

y = (x.^2+A)./(2*x);

Test the function by enter the following into the command window.

mysqrt(9)
mysqrt(2)
help mysqrt

5
14. You are now going to use the debugger on the function above.

In addition to the editor, you need to be able to see the workspace window. If you
cannot easily see the workspace window, click on the HOME tab and then click on
Layout in the ENVIROMENT section and select Default. Then maximise the
MATLAB window. Then click on the EDITOR tab.

In the editor, find the line containing x = 1; Between the line number and the line,
you will find a "-" sign on its own vertical bar. Clicking on this sign turns it into a red
dot. This is a break point. A break point is where the program will stop so that you
can debug the program. You can toggle the break point on and off by clicking on it.

With a break point set on the line noted above, run the program.

mysqrt(2)

The program will stop on the line with the breakpoint. A green arrow indicates the
next line to run. Note that the "Workspace" window is showing variables available in
the program. You can use the variable editor or the command line to change the value
of the variables.

On the icon bar you will now find the following icons.

If you put the cursor over an icon and leave it for a while, a description of what the
icon does is displayed.

The Step icon steps through the program one line at a time. Step through at least one
loop of the while loop. Notice the variables changing in the "Workspace" window.

The Step In icon is very like step, except when the line contains a call to a function.
Step will treat the function as one line of code, while Step In will step into the
function and step through the function. Try this out.

Step Out reverse a Step In. If you are inside a function, a Step Out will execute the
rest of the function, exit the function and then stop again. Step into the local function
and try a Step Out. If you hit Step Out in the top function, the program will run to
completion.

The Continue icon restarts the program from the current point in the program. It will
run to the next breakpoint or completion. Try this now.

Close the editor.

6
15. Enter the following
19. Change the title and the plot
degrees = 0:6:360; command so that a cosine wave is
rad = degrees * pi /180; plotted in green. Save as graph2.
plot(sin(rad))
20. Change the title and the plot
Close the graph and repeat the first two command so that tan is plotted in red.
commands by double clicking on them Change the y limits to -10 to 10. Save
in the Command History window. as graph3.

21. Now try a subplot command. In


16. Drag the plot command from the command window enter.
the Command History into the
command window and change it to :- subplot(3,1,1)
graph1
plot(degrees,sin(rad)) subplot(3,1,2)
graph2
See how the plot changes. subplot(3,1,3)
graph3
17. Hold down control and select
each of the following commands in the Don't forget that you can use the cursor
Command History Window, keys to recall previous commands.

degrees = 0:6:360; 22. Clear the figure and enter the


rad = degrees * pi /180; following.
plot(degrees,sin(rad))
clf
then press the right mouse button and graph1
select Create Script. hold on
Save the file as graph1.m graph2
hold off
figure
18. Annotate the graph by adding graph3
the following lines to the script.
Now delete the extra figures.
axis([0 360 -1 1])
title('Sine Wave') delete(2)
xlabel('degrees')
ylabel('value') And clear the workspace
grid clear

Observe the resulting graph.

7
23. You should have a spreadsheet Click on the white background of the
call XLfile.xls in the current directory. graph.

Double click on the file XLfile.xls Add a title "My Graph" and a grid in
the x and y directions.
Click on the green tick to import the
data. Set the XLabel to "Time" and set the
XLimits to 0 to 2*pi.
Close the import window.
Set the YLabel to "Amplitude".
If you look at the Workspace window,
you will see that the data from the Click in the Hide Plot Tools icon.
spread sheet has been imported into
MATLAB.

24. Hold down the control key and


select X and Y in the workspace
window.
From the file Menu, on the banner of
On the MATLAB icon bar, select the the figure, select
PLOTS tab. Generate Code.
Select a normal plot. Save the file to createfigure.m and
close the editor.
25. Click on the Show Plot Tools icon
on the figure icon bar. 26. Run the M file you have just
created.

createfigure(X,Y)

Click on the line of the graph.

Try different line styles, thickness and


colour.

Try different markers. Change the size


of the markers and try different fill and
line colours.

You might also like