Assignment_final
Assignment_final
balance = 1000;
rate = 0.09;
interest = rate * balance;
balance = balance + interest;
disp( 'New balance:' );
disp( balance );
Q2:
2.1. Give values to variables a and b on the command line—for example, a=3 and b=5.
Write statements to find the sum, difference, product, and quotient of a and b.
Type this into the editor, save it, and execute it.
Q3:
3.1. Enter a statement like x = [1 3 0 –1 5]
Can you see that you have created a vector (list) with five elements?
Enter the command disp(x) to see how MATLAB displays a vector.
Enter the command whos (or look in the Workspace browser). Under the heading Size
you will see that x is 1 by 5, which means 1 row and 5 columns. You will also see that
the total number of elements is 5.
3.2 You can use commas instead of spaces between vector elements if you like.
Try this: a = [5,6,7]
3.3 You can use one vector in a list for another one. Type in the following:
a = [1 2 3];
b = [4 5];
c = [a –b];
Can you work out what c will look like before displaying it?
And what about this?
a = [1 3 7];
a = [a 0 –1];
Q2:
2.1. Evaluate the following expressions yourself (before you use MATLAB to check).
The numerical answers are in parentheses.
(a) 2 / 2 * 3 (3)
(b) 2 / 3 ˆ 2 (2/9)
(c) (2 / 3) ˆ 2 (4/9)
(d) 2 + 3 * 4 – 4 (10)
(e) 2 ˆ 2 * 3 / 4 + 3 (6)
(f) 2 ˆ (2 * 3) / (4 + 3) (64/7)
(g) 2 * 3 + 4 (10)
(h) 2 ˆ 3 ˆ 2 (64)
(i) –4 ˆ 2 (–16; ˆ has higher precedence than –)
2.2. Use MATLAB to evaluate the following expressions. The answers are in
parentheses.
(a) (1.4142; use sqrt or ˆ0.5)
(b) (0.6364; use brackets)
(c) Find the sum of 5 and 3 divided by their product (0.5333)
(d) (512)
(e) Find the square of 2π (39.4784; use pi)
(f) (19.7392)
2.3. Try to avoid using unnecessary brackets in an expression. Can you spot the errors
in the following expression? (Test your corrected version with MATLAB.)
(2(3+4)/(5*(6+1))ˆ2
Note that the MATLAB Editor has two useful ways of dealing with the problem of
―unbalanced delimiters‖ (which you should know about if you have been working
through Help!):
■ When you type a closing delimiter, that is, a right ), ], or }, its matching
opening delimiter is briefly highlighted. So if you don’t see the highlighting
when you type a right delimiter, you immediately know you’ve got one too
many.
■ When you position the cursor anywhere inside a pair of delimiters and select
Text→Balance Delimiters (or press Ctrl+B), the characters inside the
delimiters are highlighted.
Q3:
3.1 Set up a vector n with elements 1, 2, 3, 4, 5. Use MATLAB array operations on it to
set up the following four vectors, each with five elements:
(a) 2, 4, 6, 8, 10
(b) 1/2, 1, 3/2, 2, 5/2
(c) 1, 1/2, 1/3, 1/4, 1/5
(d) 1, 1/22, 1/32, 1/42, 1/52
3.3. Water freezes at 32◦ and boils at 212◦ on the Fahrenheit scale. If C and F are
Celsius and Fahrenheit temperatures, the formula
F = 9/5C + 32
converts from one to the other. Use the MATLAB command line to convert Celsius 37 ◦
(normal human temperature) to Fahrenheit (98.6◦).
C = 37;
F = C*9/5 + 32;
disp(F);
Assignment 3:
Chapter 2: Arrays: vectors and matrices - Repeating with for loop
Q3: OUTPUT
3.1. The disp statement:
General form of disp for a numerical variable is:
disp (variable)
To display a message and a value on the same line, use the following trick:
x = 2;
disp( [’The answer is ’, num2str(x)] );
The output should be
The answer is 2
Q4: Factorials!
Run the following program to generate a list of n and n! (―n factorial,‖ or ―n shriek‖),
where
n! = 1 × 2 × 3 × . . . × (n − 1) × n
n = 10;
fact = 1;
for k = 1:n
fact = k * fact;
disp( [k fact] )
end
Experiment to find the largest value of n for which MATLAB can find the n factorial.
sign = -1;
s = 0;
for n = 1:99
sign = -sign;
s = s + sign / n;
end
Homework:
Write MATLAB programs to find the following sums with for loops and by vectorization.
12 + 22 + 32 +· · ·+10002
1-
Sum the left-hand side of the series:
Solution:
12 + 22 + 32 +· · ·+10002 (sum is 333 833 500)
s = 0; % with for loop
for i = 1:1000
s = s + i^2;
end
disp(s);
a = 1:1000; % by vectorization
s = sum(a.^2);
1- (0.7849)
sign = -1; % with for loop
s = 0;
for i = 1:2:1003
sign = -sign;
s = s + sign/i;
end
disp(s);
a = 1:4:1001; % by vectorization
b = 3:4:1003;
s = sum(a.\1) - sum(b.\1);
If statement
if condition1
statementsA
elseif condition2
statementsB
elseif condition3
statementsC Logical operators
... More complicated logical expressions
can be constructed using the three
else
logical operators:
statementsE & (and), | (or), and ˜ (not).
end
if (b ˆ 2 - 4*a*c == 0) & (a ∼= 0)
x = –b / (2*a);
end
d = bˆ 2 – 4*a*c;
if a ∼= 0
if d < 0
disp( ’Complex roots’ )
else
x1 = (–b + sqrt( d )) / (2*a);
x2 = (–b – sqrt( d )) / (2*a);
end % first end ««««««
end
Q2: switch – case statement:
d = floor(3*rand) + 1
switch d
case 1
disp( ’That’’s a 1!’ );
case 2
disp( ’That’’s a 2!’ );
otherwise
disp( ’Must be 3!’ );
end
Multiple expressions can be handled in a single case statement by enclosing the case
expression in a cell array
d = floor(10*rand);
switch d
case {2, 4, 6, 8}
disp( ’Even’ );
case {1, 3, 5, 7, 9}
disp( ’Odd’ );
otherwise
disp( ’Zero’ );
end
Chapter 3: Program Design and Algorithm Development:
Review of basic elements:
- Input
Initialize, define, request, or assign numerical values to variables.
- Set of commands
Operations applied to input variables that lead to the desired result.
- Output
Display (graphically or numerically) result.
%
F = input(‘Temperature in degrees F: ‘);
C = (F-32)*5/9;
disp([ ‘Temperature in degrees C = ‘,num2str(C)])
% STOP
% Step 1: Start
format compact
disp(' ')
disp(' Quadratic roots finder ')
disp(' ')
% Step 2: Input data
A = input(' Specify coefficients as follows: [a, b, c] = ');
a = A(1);b = A(2);c = A(3);
% Step 3: Evaluation of roots
if a==0 & b==0 & c==0
disp(' Solution is indeterminate ')
elseif a==0 & b==0
disp(' There is no solution ')
elseif a==0
x = -c/b
disp(' Only one root: equation is linear.')
elseif b^2 - 4*a*c < 0
disp(' Complex roots')
elseif b^2 - 4*a*c == 0
x = -b/(2*a)
disp(' Equal roots')
elseif b^2 - 4*a*c > 0
x1 = (-b + sqrt(b.^2-4.*a.*c) )./(2.*a);
x2 = (-b - sqrt(b.^2-4.*a.*c) )./(2.*a);
disp(' x1,x2 the two distinct roots')
disp([x1 x2])
end
format
% Step 4: Stop
Chapter 4: MATLAB Functions and Data Import–Export
Utilities:
1- Common functions:
Note that if the argument of a function is an array, the function is applied element by
element to all the values in the array.
For example, sqrt([1 2 3 4])
returns 1.0000 1.4142 1.7321 2.0000
If you view myData.txt in a text editor (or type it in the Command Window)
it looks like this:
1.0000000e+000 2.0000000e+000 3.0000000e+000
4.0000000e+000 5.0000000e+000 6.0000000e+000
1- Logical Operators:
Example,
˜0 & 0 returns 0 (false), whereas
˜(0 & 0) returns 1 (true).
Some more examples:
(b * (b == 4) * a * c) & (a ˜= 0)
(final >= 60) & (final < 70)
(a ˜= 0) | (b ˜= 0) | (c != 0)
˜((a == 0) & (b == 0) & (c == 0))
3- Logical Functions:
any(x) returns the scalar 1 (true) if any element of x is nonzero (true).
all(x) returns the scalar 1 if all elements of x are nonzero.
* Because any and all with vector arguments return scalars, they are
particularly useful in if statements.
* if all(a >= 1) if any(a ˜= b)
do something do something
end end
exist(’a’) returns 1 if a is a workspace variable.
find(x) returns a vector containing the subscripts of the nonzero (true) elements of x.
* a = a( find(a) ) removes all zero elements from a.
* x = [8 1 –4 8 6];
find(x >= max(x)) returns the vector [1 4], which comprises the subscripts
of the largest element.
isempty(x) returns 1 if x is an empty array and 0 otherwise
isinf(x) returns 1s for the elements of x that are +Inf or –Inf, and 0’s otherwise.
isnan(x) returns 1s where the elements of x are NaN, and 0’s otherwise.
ischar() returns 1 if () contains character data
isnumeric() returns 1 if () contains numeric data
Exercise:
x = 0 : pi/20 : 3 * pi;
y = sin(x);
y = y .* (y > 0); % set negative values of sin(x) to zero
plot(x, y)
When x has the value eps, the value of sin(eps)/eps has the correct limiting
value of 1 (check it) instead of NaN (Not-a-Number) resulting from a division
by zero.
r = rand(1,7) % no semi-colon
2. Check that the logical expression r < 0.5 gives the correct logical vector. Using the
function sum on the logical expression r < 0.5 will effectively count how many elements
of r are less than 0.5. Try it and check your answer against the values displayed for r:
sum( r < 0.5 )
4- Rolling dice
When a fair die is rolled, the number uppermost is equally likely to be any integer from 1
to 6. Thus, if rand is a random number in the range [0, 1), 6 * rand will be in the range 0,
6) and 6 * rand + 1 will be in the range [1, 7), that is, between 1 and 6.9999. Discarding
the decimal part of this expression with floor gives an integer in the required range.
Homework
5.1. Determine the values of the following expressions yourself before checking your
answers using MATLAB. You may need to consult Table 5.3.
(a) 1 & –1
(b) 13 & ˜(–6)
(c) 0 < –2|0
(d) ˜[1 0 2] * 3
(e) 0 <= 0.2 <= 0.4
(f) 5 > 4 > 3
(g) 2 > 3 & 1
5.2. Given that a = [1 0 2] and b = [0 2 2], determine the values of the following
expressions. Check your answers with MATLAB.
(a) a ˜= b
(b) a < b
(c) a < b < a
(d) a < b < b
(e) a | (˜a)
(f) b & (˜b)
(g) a|(˜(˜b))
Chapter 6: Matrices of numbers and arrays of strings:
Learning objectives:
■ Creating and manipulating matrices
■ Introduction to matrix operations
■ Introduction to character strings and facilities for handling them
6.1 MATRICES
Example: Transportation problem:
Transportation costs Supply-Demand
To calculate the total transportation in MATLAB, enter C and X as matrices from the
commands:
C = [3 12 10; 17 18 35; 7 10 24];
X = [4 0 0; 6 6 0; 0 3 5];
and then find the array product of C and X:
total = C .* X
which gives
12 0 0
102 108 0
0 30 120
The command
sum(total)
then returns a vector where each element is the sum of each column of total:
114 138 120
Summing this in turn—that is,
sum(sum( total )) —gives the final answer of
372.
Creating matrices
Bigger matrices can be constructed from smaller ones; for example, the statements
a = [1 2; 3 4]; a= 1 2
x = [5 6]; 3 4
a = [a; x] 5 6
Subscripting:
For the above example:
a(3,2) returns 6 a(5) returns 4
a(3,3) = 7; will add a third column to a with 0s everywhere except at a(3,3).
The transpose operator (’)
a = [1:3; 4:6]
b = a’
result in
a=
1 2 3
4 5 6
b=
1 4
2 5
3 6
The colon operator (:)
For example, if a is the matrix
a=
1 2 3
4 5 6
7 8 9
the statement
a(2:3,1:2)
results in
4 5
7 8
The statement
a(3,:)
results in
7 8 9
Finally, the statement
a(1:2,2:3) = ones(2)
results in
a=
1 1 1
4 1 1
7 8 9
the statement
a(2,:) = a(2,:) – a(2,1)*a(1,:)
subtracts the first row multiplied by the first element in the second row from the second
row, resulting in
a=
1 –1 2
0 3 –5
3 0 1
The keyword end refers to the last row or column of an array. For example, if r is a row
vector, the statement
sum(r(3:end))
returns the sum of all the elements of r from the third one to the last one.
The colon operator may also be used as a single subscript, on the right-hand side, a(:)
gives all the elements in one long column vector. Thus, if
a=
1 2
3 4
the statement
b = a(:)
results in
b=
1
3
2
4
However, on the left-hand side of an assignment, a(:) reshapes a matrix that already
exists, i.e., the matrix on the right-hand side is reshaped into the shape of a on the left-
hand side. If
b=
1 2 3
4 5 6 and
a=
0 0
0 0
0 0
the statement
a(:) = b
results in
a=
1 5
4 3
2 6
a(:) = 1:6
(with a as above) results in
a=
1 4
2 5
3 6
a(:) = –1
replaces all the elements of a matrix with a scalar:
Manipulating matrices
Here are some functions for manipulating matrices (See Help for details):
■ diag extracts or creates a diagonal.
■ fliplr flips from left to right.
■ flipud flips from top to bottom.
■ rot90 rotates.
■ tril extracts the lower triangular part
■ triu extracts the upper triangular part.
6.4 STRINGS
Strings may be assigned to variables by enclosing them in apostrophes:
s = ’Hi there’;
If an apostrophe is part of the string, it must be repeated:
s = ’o’’clock’;
Input
Strings may be entered in response to the input statement in two ways:
■ Enclose the string in apostrophes when you enter it.
■ Use an additional argument ’s’ with input
name = input( ’Enter your surname: ’, ’s’ );
Strings as arrays
A MATLAB string is actually an array, with each element representing one character.
For example, if
s = ’Napoleon’
whos reveals that s is 1 by 8. The statement
s(8:–1:1)
will therefore display the string Napoleon backwards.
The following code will remove all the blanks from the string s.
s = ’Twas brillig and the slithy toves’;
nonblanks = s ˜= ’ ’;
s(nonblanks)
nonblanks is a logical vector with 0s corresponding to the positions of the blanks. Using
nonblanks as a subscript removes the blanks.
String concatenation
Because strings are vectors, they may be concatenated (joined) with square brackets:
king = ’Henry’;
king = [king, ’ VIII’]
You can see that the ASCII codes for a string with double:
double(’Napoleon’)
return
78 97 112 111 108 101 111 110
Suppose an experiment calls for a coin to be flipped 50 times and the results to
be recorded. In real life you may need to repeat such an experiment a number
of times; this is where computer simulation is handy.
for i = 1:50
r = rand;
if r < 0.5
fprintf( ’H’ )
else
fprintf( ’T’ )
end
end
fprintf( ’\n’ ) % newline
ROLLING DICE
When a fair die is rolled, the number uppermost is equally likely to be any
integer from 1 to 6. The following statement generates a vector with 10 random integers
in the range 1–6:
d = floor( 6 * rand(1,10) + 1 )
Here are the results of two such simulations:
2155634511
4513135466
EXERCISES
1. Draw lines joining the following points: (0, 1), (4, 3), (2, 0), and (5,−2).
plot([0 4 2 5], [1 3 0 -2])
Labels:
grid adds/removes grid lines to/from the current graph.
text(x, y, ’text’) writes text in the graphics window at the point specified by x and y.
title(’text’) writes the text as a title at the top of the graph.
xlabel(’horizontal’) labels the x-axis.
ylabel(’vertical’) labels the y-axis.
If you are plotting two graphs on the same axes, you may find plotyy useful—it allows
you to have independent y-axis labels on the left and the right:
plotyy(x,sin(x), x, 10*cos(x))
Line styles, markers, and color
For example,
plot(x, y, ’--’) joins the plotted points with dashed lines, whereas plot(x, y, ’o’) draws
circles at the data points with no lines joining them.
You can specify all three properties:
plot(x,sin(x), x, cos(x), ’om--’)
which plots sin(x) in the default style and color and cos(x) with circles joined by dashes
in magenta. The available colors are denoted by the symbols c, m, y, k, r, g, b, w.
Axis limits
Whenever you draw a graph, MATLAB automatically scales the axis limits to fit
the data. You can override this with
axis( [xmin, xmax, ymin, ymax] ) which sets the scaling on the current plot.
THREE-DIMENSIONAL PLOTS
The plot3 function
The function plot3 is the 3D version of plot. The command
plot3(x, y, z)
draws a 2D projection of a line in 3D through the points whose coordinates are the
elements of the vectors x, y, and z
Example:
t = 0:pi/50:10*pi;
plot3(exp(–0.02*t).*sin(t), exp(–0.02*t).*cos(t),t)
xlabel(’x-axis’), ylabel(’y-axis’), zlabel(’z-axis’)
Chapter 8: LOOPS:
DETERMINATE REPETITION WITH for
ncr = 1;
n = 10;
r = 3;
for k=1:r
ncr = ncr*(n-k+1)/k;
end
disp (ncr)
120
Try it out a few times. Note that the while loop repeats as long as num is not equal to
guess.