Home, Matlab exercise 1, Matlab exercise 2, Matlab exercise 3.
False (=0) / True (=1):
>> 2<3
>> 2>3
>> -3<2
>> 1+1 = = 2
>> 2 = = 3
>> 2 ~= 3
==================
Conditional statements:
>> i=1;
>> if i = = 1 disp('i is one'); end
>> i=2
>> if i = = 1 disp('i is one'); end
>> if i = = 1 disp('i is one'); else disp('i is not one'); end
>> help if
======================
Script files:
>> edit
>> hello
Replace disp('hi') by code that sorts a list/vector v=[a b],
that is, gives v=[a b] if a < b and v=[b a] if b < a, for example
if v(1) < v(2)
elseif v(2) < v(1)
end
v
if v(2) < v(1)
end
v
>> v=[2 1]
>> MyFirstSort
>> MyFirstSort
What happens in the two code versions if v(1)=v(2)?
===================
Loops, for and while:
Write code that makes the computer count to a given number N, for
example.
i=0;
while i < N
end
>> N=10;
>> CountToN
Alternative code construction
for i=1:N
end
>> CountToN2
Exercises:
1. a) Get the computer to count only the odd numbers up to N. Hint:
elegant to use the for loop with i=1:2:N.
b) Get the computer to count backwards from N down to 1, first with
a "for loop" (hint: elegant to just replace i=1:N by i=N:-1:1),
then with a "while loop".
2. Write code that for a given number N tests whether 1+2+..+N = N^2/2
by computing 1+2+..+N and N^2/2, and display their difference and
ratio. What is the ratio for N=1000? Explain why two numbers with a
considerable difference can have a ratio very close to one!
3. Given natural numbers m and n, have matlab find p and r with 0<=r < n
such that m=pn+r. Try the following code
p=0;
r=m;
while r>=n
end
disp(['m=' num2str(p) 'n+' num2str(r)])
pos=0;
while pos<1
end
while 1<2
end
6. Try and then seek to understand the following code?
while 1
end
============================
Computer arithmetic:
>> eps
>> eps/2
>> eps/100000000000000
>> help eps
>> 1+eps = = 1
>> 1+eps/2 = = 1
>> a=10
>> a=a^2
>> Inf=Inf+1
>> Inf*2
>> Inf/2
>> 1/eps
>> 1/0
>> -1/0
>> 0/0
>> Inf-Inf
>> Inf/Inf
>> 0*Inf
Exercises:
1. Seek the largest number less than Inf, according to matlab.
========================
Composite conditions:
>> 0<=1
>> 1<=1
>> 1<2 | 1>2
>> 1<2 & 1>2
>> ~(1<2)
Last modified: Sat Sep 8 18:21:14 MET DST 2001