Академический Документы
Профессиональный Документы
Культура Документы
1. MATLAB desktop
Command window:
Current Directory pane:
(File) Details pane :
Workspace pane:
Evaluate the MATLAB expressions
1+2/3*4-5
1/2/3/4
1/2+3/4*5
5-2*3*(2+7)
(1+3)*(2-3)/3*4
(2-3*(4-3))*4/5
EXERCISES
in seven different
3 1 . 4 1 59
3 . 1 4 1 6e+00 1
3 1 . 4 1 592653589793
3 . 141592653589793e+001
31.416
31.4159265358979
403f6a7a2955385e
3550/ 1 1 3
3 1 . 42
s = linspace(0,1);
t = linspace(0,1,10);
q4.Construct the function y = x2/ (x3+ 1)for values of x from one to two in
steps of 0.01.
Example 1.20 Construct the function f(x) = x2+2 on the set of points x = 0
to2 in steps of 0.1 and give the value of f(x) at x = 0, x = 1 and x = 2.
Q8.Calculate the values of the following expressions
p(x) = x2 + 3x + 1 atx = 1.3,
y(x) = sin(x) atx = 30,
f(x) = tan1(x) at x = 1,
hints (atan(x))
1
g(x) = sin(cos (x))at x =3/2
Q9.Calculate the value of the function y(x) = |x| sin x2 for values of
x = /3 and /6 (use the MATLAB command abs(x) to calculate |x|).
Q10.Calculate the quantities sin(/2), cos(/3), tan 60 and ln(x +
x2 + 1) where x = 1/2 and x = 1. Calculate the expression x/((x2 +1) sinx)
wherex = /4 and x = /2. (If you are getting strange answers in the form
EXbalance = 1000;
rate = 0.09;
interest = rate * balance;
Example 2.5 As you might expect a function can have multiple inputs and
outputs:
(save.multi.m file)[
function [out1,out2] = multi(in1,in2,in3)
out1 = in1 + max(in2,in3);
out2 = (in1 + in2 + in3)/3;]
exx1 = 2; x2 = 3; x3 = 5;
[y1,y2] = multi(x1,x2,x3);
y1, y2
Logical operators
Operation:
Logical and
Logical or
Negate
MATLAB command:
&
|
~
Relational operators
Operation:
Strictly less than
Less than or equal to
Strictly greater than
Greater than or equal to
Equal to
Not equal to
MATLAB command:
<
<=
>
>=
==
~=
1. The easiest way is simply to use hold to keep the current plot on the axes.
All subsequent plots are added to the axes until hold is released, either with
hold off or just hold, which toggles the hold state.
2. The second way is to use plot with multiple arguments, e.g.
plot(x1, y1, x2, y2, x3, y3, ... )
if logical expression
commands
else
commands
end
Note that for each if,, you need to "close" the if-statement
statement with an end. Make
sure the if:s and end:s always match! (This is a common source for programming
errors.)
1.
Conditional Expressions
% displays 1
% displays 1
disp(x == y);
% displays 0
% displays 1
You can even perform logical operations on arrays. The operations are performed
cell-by-cell and the output is an array of logical values:
area=[ 1 4 9 16 25 36 ];
perimeter=[ 4 8 12 16 20 24 ];
disp(area < perimeter);
% displays 1 1 1 0 0 0
Finally, you can use a logical array to select elements from a numerical array.
Cells from the numerical array that match true values in the logical array are
extracted. Just use the logical array in the place of the subscript operator, e.g.:
disp(area(area < perimeter));
% displays 1 4 9
Example 2.
clear
N = input('Give numerator: ');
D = input('Give denominator: ');
if D==0
'Sorry, cannot divide by zero'
else
ratio = N/D
end
If Statement
The condition should be a logical expression evaluating to true or false. if (x < 10)
disp(x);
end
if ((0 < x) & (x < 100))
disp('OK');
end
You can put more than one statement between the if and the end. You can
choose between two courses of action with if condition statement else statement
end as in:
if ((0 < x) & (x < 100))
disp('OK');
else
disp('x contains invalid number');
end
You can build a chain of tests with elseif, as in:
if (n <= 0)
disp('n is negative or zero');
elseif (rem(n,2)==0)
disp('n is even');
else
disp('n is odd');
end
You can embed, or nest statements, as in: (What function does this code
calculate?)
if (a < b)
if (a < c)
disp(a);
else
disp(c);
end
else
if (b < c)
disp(b);
else
disp(c);
end
end
In the next example, we make MATLAB write something depending on which test
our month "passes". To make MATLAB write text as output, use single quote '
around the text.
Example 3.
clear
month = input('Give month number (1-12): ' );
if month==1
month==10 |
'Your month
else
if month==2
'Your month
else
'Your month
end
end
has 28 days'
has 30 days'
In the next example we use the command rem (remainder). The syntax is
rem(x,y)
and returns the remainder after the division of the two integers x and y.
Example 4.
clear
number = input('Give an integer: ' );
remainder2 = rem(number,2);
remainder3 = rem(number,3);
if remainder2==0 & remainder3==0
'Your number is divisible by both 2 and 3'
else
if remainder2==0
'Your number is divisble by 2 but not by 3'
else
if remainder3==0
'Your number is divisible by 3 but not by 2'
else
'Your number is not divisible by either 2 or 3'
end
end
end
Exercise 1.
Write a "currency exchange program" similar to the one in Example 1 which can
handle two different exchange rates, exchange_rate1 = 0.5 and exchange_rate2 =
0.25. Design the program to first ask for the amount in dollars and then ask the
user which rate (represented
epresented by the numbers 1 and 2 respectively) he/she wants.
Let the program return the amount in the requested foreign currency.
.
Example 5.
clear
for i=1:2:20
x(i)=i/7;
end
x
In the following example we see a so-called nested for-loop. This is nothing else
then a "loop within a loop". Note how we must "close" each for with an end.
Make sure you understand how this example works!
Example 6.
clear
for i=1:5
for j=1:5
A(i,j)=10*i+j;
end
end
A
In the following example, make sure you understand the purpose of the variable
mysum. This is a common way of performing summations when programming.
Example 7.
clear
mysum = 0;
for k=0:10
mysum = mysum+1/gamma(k+1);
end
e_approximation = mysum
e_exact = exp(1)
In the next example, notice how we have to "shift" the indexing of the vector.
MATLAB must have non-zero, positive integers as vector- or matrix-indices!
One of the most common mistakes when programming in MATLAB is that your
program begins indexing at zero instead of one. Also note how by typing a percent
sign (%) before text in the code, MATLAB does not interpret this text as code. It
just serves as a comment for any person using the code. Commenting your code is
essential when writing programs.
Example 8.
clear
for k=0:70
x(k+1)=0.1*k; % Indices of vectors must be NON-ZERO!
sum = 0;
for m=0:10
sum = sum+(x(k+1)^m)/gamma(m+1); % Approx exp(x) using
its Taylor series
end
e(k+1) = sum; % e(k+1) contains the Taylor series
approx. for x=x(k+1);
end
semilogy(x,e)
title('Approximation of e^x for x between 0 and 7')
xlabel('x')
ylabel('e^x')
Exercise 2.
Write a program that approximates PI by computing the sum
.
The more terms you keep in the summation, the more accurate your answer will
be. (In fact, the series converges to PI as m goes to infinity.) See how many terms
you need to approximate PI with 5 decimals. (Note: This is by no means the most
efficient way to approximate PI, but the formula is quite beautiful...)
Exercise 3
Write a program (that asks the user for an age and then classifies the age
according to the following scheme:
Error < 0 <= Baby < 1 <= Child < 13 <= Teenager < 18 <= Adult < 60
<= Senior < 120 <= Error
For example:
Enter an age: 25
Adult
2.
F = (C x 2) + 30