numerical analysis 3 rd
Page
of 3
ZOOM
Programming with MatLab
In this exercise, you are provided with an example problem and a practice problem. Run the example
problem in MATLAB to see how it works then complete the practice problem.
1. What does a statement such as z = 10 signify?
Answer: A statement such as z = 10 creates a variable named z, stores the value 10 in it,
and saves it in a part of computer memory known as the workspace.
Example 1:
Evaluate:
x = 3
y = 4
x
2
y
3
/ (x-y)
2
MATLAB PROGRAM:
(x^2*y^3)/(x-y)^2
ans = 576
Practice 1:
Use MATLAB to evaluate the following expression:
x =2, y = -1
1)
푥
2
푦
3
(푥
‒
푦)
2
3)
2)
4
2푥
3
4
2푦
3
__________________________________________________________________________
Example 2:
MATLAB program:
% This m-file calculates the area of a circle
% and displays the result.
radius = 2.5;
area = pi * radius ^2;
string = [‘The area of the circle is ’ num2str(area)];
disp(string);
Practice 2:
Calculate the volume of a cylinder of length = 0.5 m if the radius = 0.1m using the equation:
Volume = area of the base * length
Display the area and the volume the same way you did for the problem to calculate area.
_____________________________________________________________________________________
Example 3: sin x
% sin_x.m: This m-file calculates and plots the
% function sin(x) for 0 <= x <= 6.
x = 0:0.1:6
y = sin(x);
plot(x,y);
Practice 3:
Use MATLAB to plot absolute value of sin(t) between -2pi and 2pi with an increment of pi/10.
Hint: abs() is the command for absolute value.
____________________________________________________________________________________
Example 4:
Input commands
Use MATLAB to write a small program called
asking
to prompt a user for his/her name,
after the user enters the name, the program outputs “Your name is
(name the user
inputs)
”.
ask = input ('What is your name? \n', 's');
response = ['Your name is ', ask];
disp (response)
The output is
>> asking
What is your name?
Carl
Your name is Carl
Practice 4:
Use MATLAB to write a small program called
Mailing
to prompt a user for his/her name,
and address after the user enters the name and the address, the program outputs the name
and address with the exact format of a mailing address that you will place on top of an
envelope to mail at the post office.
_____________________________________________________________________________________
Practice Problem 5:
1. With MATLAB use the Bisection method to find
p
3
for f(x) = x
3
– 9.
Write down an interval that contains a solution. (Read the lesson on Bisection technique
before solving this problem).