Вы находитесь на странице: 1из 22

MATLAB windows

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

General commands you should remember

round(x) Rounds a number to the nearest integer


ceil(x)
Rounds a number up to the nearest integer
floor(x)
Rounds a number down to the nearest integer
fix(x)
Rounds a number to the nearest integer
towards zeroZW2
rem(x,y) The remainder left after division
mod(x,y) The signed remainder left after division
abs(x)
The absolute value of x
sign(x)
The sign of x
factor(x) The prime factors of x
Output format :
The following table shows the printed value of l0
formats .
f o rmat short
f ormat short e
f ormat l ong
f o rmat long e
f ormat short g
f ormat long g
f o rmat hex
f o rmat rat
f ormat bank

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

q4. s = [1/2 1/3 pi sqrt(2)]; give result all outpot formate.

1.4.1 Initialising Vector Objects


r = 1:2:5;
s = 1:0.5:3.5;

s = linspace(0,1);
t = linspace(0,1,10);

1.4.2 Manipulating Vectors and Dot Arithmetic


>> a = [1 2 3];
>> 2*a;
>> a = [1 2 3];
>> b = [4 5 6];
>>a*b
>> a.*b
Q3 s = 1:6;
t = 6:-1:1;
s+t
s-t
s.*t
s./t
s.2
1./s
s/2
54s+1

q4.Construct the function y = x2/ (x3+ 1)for values of x from one to two in
steps of 0.01.

q5.Construct the function


y(x) = sin(x cosx/ x2+ 3x + 1) for values of x from one to three in steps of
0.02.
MATLAB Specific Commands
We shall now introduce a couple of commands which can be used to make
calculations
where the input can take a variety of forms. The first command is
polyval. This command takes two inputs, namely the coefficients of a
polynomial
and the values at which you want to evaluate it.

It is important that you remember to enter the coefficients of the


polynomial starting with the one associated with the highest power
and that zeros are included in the sequence.
Q6.Evaluate the cubic y = x3+ 3x2 x 1 at the points x =
(1, 2, 3, 4, 5, 6). We provide the solution to this example as a commented
code:
Sol: % Firstly set up the points at which the polynomial
% is to be evaluated
x = 1:6;
% Enter the coefficients of the cubic (note that
% these are entered starting with the
% coefficient of the highest power first
c = [1 3 -1 -1];
% Now perform the evaluation using polyval
y = polyval(c,x)
q7.Plot the polynomial y = x4+x21 between x = 2 and x = 2
(using fifty points).

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

q11.Compare the MATLAB functions rem(x,y) and mod(x,y) for a variety


of values of x and y (try x = 3, 4, 5 and y = 3, 4,4, 6).

q12.Evaluate the function


Y=1/x3 +1/x2 +3/x
forx = 2 to x = 1 in steps of 0.1.

EXbalance = 1000;
rate = 0.09;
interest = rate * balance;

balance = balance + interest;


disp( New balance: );
disp( balance );

2.1 Creating Scripts and Functions


Exa = input(First number );
b = input(Second number );
c=a+b;
d=a*b;
disp([Their sum is num2str(c)])
disp([Their product is num2str(d)])

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

Relational and logical operators


This heading may sound scary but it is really just a fancy name for some of the
fundamental operators used for programming. Below follows a list with some
useful commands.

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:
<
<=
>
>=
==
~=

Some Useful MATLAB commands

Creating and Printing S imple Plots


The MATI,AB commands used are
plot
creates a 2-D
D line plot ,
ax i s
changes the aspect ratio o f the x-axis
x
and the y-axis,
x l ab el annotates the x--axis,
ylab e l annotates the y-axis,
y
t it l e
puts a title o n the plot
pr int
prints a hard copy of the plot .
gridon
add gride
1.plot a simple graph
>>x = 0:pi/40:4*pi;
plot(x, sin(x))
2. to draw a line between the point with cartesian coordinates (0, 1) and (4, 3)
use the statement
>>plot([0 4], [1 3])

3. Plot a graph with lable


>> theta = linspace (0, 2 *pi , l00) ;
>> x =c o s ( theta) ;
>> y == s in (theta ) ;
>>p l o t (x, y)

Create a linearly spaced 1 00-elements.

>>axi s ( ' equa l ' ) ;


length scales , two axes to be the same.
>>title ('Circle of un it radius ' )
Put a title on the plot.
Multiple plots on the same axes

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

We have seen a number of arithmetical expressions using operators such as +,


and *. We can also create logical or conditional expressions using comparison
compa
and Boolean operators. Such expressions always produce a numerical result that is
either 1 for true expressions, or 0 for false expressions. The comparison operators
are <, <=, ==, >=, > and ~=. The Boolean operators are & (and), |

(or), ~ (not). You can use parentheses to bracket expressions to force an


evaluation order. For example:
x=10;
y=20;
disp(x < y);
disp(x <= 10);

% displays 1
% displays 1

disp(x == y);

% displays 0

disp((0 < x) & (y < 30)); % displays 1


disp((x > 10) | (y > 100)); % displays 0
disp(~(x > 10));

% 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);

% only displays x when x < 10

end
if ((0 < x) & (x < 100))
disp('OK');

% displays OK if x between 0 and 100

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

| month==3 | month ==5 | month==7 |


month==12
has 31 days'

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.

Repetitive operations (loops)

for loop variable = startvalue : endvalue


commands
end

.
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.

Print a Fahrenheit to Celsius Conversion table for each 5 degrees between 0


and 100 Fahrenheit .

F = (C x 2) + 30

Вам также может понравиться