Download Basic exercises

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mathematics of radio engineering wikipedia , lookup

Elementary mathematics wikipedia , lookup

Addition wikipedia , lookup

Transcript
Basic exercises
1. x = 32:2:75
2. x
a
b
c
d
=
=
=
=
=
[2 5 1 6]
x + 16
x(1:2:end) + 3
sqrt(x) or c = x.^(0.5)
x.^2 or d = x.*x
3. x = [3 2 6 8]', y = [4 1 3 5]'
a = y + sum(x)
b = x.^y
c = x./y
z = x.*y
w = sum(z)
x'*y - w
(same thing)
5. The function "rats" just displays the contents of a variable
a = 2:2:20 (or whatever max #)
b = 10:-2:-4
c1 = 1:5, c2 = 1./c1 , rats(c2)
d1 = 0:4, d2 = 1:5, d3 = d1./d2 , rats(d3)
6. n = 1:100;
x = ( (-1).^(n+1) ) ./ (2*n - 1);
y = sum(x)
8. t
a
b
c
d
e
f
=
=
=
=
=
=
=
1:0.2:2
log(2 + t + t.^2)
exp(t).*(1 + cos(3*t))
cos(t).^2 + sin(t).^2 (all ones!)
atan(t)
cot(t)
sec(t).^2 + cot(t) - 1
12. t = 1790:2000;
term = 1 + exp(-0.0313*(t - 1913.25));
P = 197273000./term;
plot(t,P)
xlabel('year'), ylabel('population')
P2020 = 197273000/(1 + exp(-0.0313*(2020 - 1913.25)))
Array exercises
2. A = [ 2 4 1 ; 6 7 2 ; 3 5 9]
x1 = A(1,:)
y = A(end-1:end,:)
c = sum(A)
d = sum(A,2) or d = sum(A')'
N = size(A,1), e = std(A)/sqrt(N)
5. A
B
C
c
d
e
=
=
=
=
=
=
[2 7 9 7 ; 3 1 5 6 ; 8 1 2 5]
A(:,2:2:end)
A(1:2:end,:)
reshape(A,4,3) or c = A' (they are different but are both 4x3)
1./A , rats(d)
sqrt(A)
6. randn('seed',123456789)
F = randn(5,10);
N = size(F,1)
avg = mean(F)
s = std(F)
tscore = (avg - 0)./(s/sqrt(N))
None were different at 90% LOC (all < 2.132).
Relational/Logical exercises
4. x
a
b
c
=
=
=
=
[3
x,
x,
x,
15 9
idxa
idxb
idxc
12 -1 0 -12 9 6 1]
= x > 0,
a(idxa) = 0
= ~rem(x,3), b(idxb) = 3
= ~rem(x,2), c(idxc) = 5*c(idxc)
5. x = 1:35;
y = zeros(size(x));
idx1 = x < 6;
idx2 = (x >= 6) & (x < 20);
idx3 = (x >= 20) & (x <= 35);
y(idx1) = 2;
y(idx2) = x(idx2) - 4;
y(idx3) = 36 - x(idx3);
disp([x(:) idx1(:) idx2(:) idx3(:) y(:)])
plot(x,y,'o')
Loop constructs: The answers here provide one version of the solutions. Alternatives are possible
and encouraged, especially where time and efficiency of the code is important.
1. x = [1 8 3 9 0 1]
a. total = 0;
for j = 1:length(x)
total = total + x(j);
end
b. runningTotal = zeros(size(x));
runningTotal(1) = x(1);
for j = 2:length(x)
runningTotal(j) = runningTotal(j-1) + x(j);
end
c. s = zeros(size(x));
for j = 1:length(x)
s(j) = sin(x(j));
end
2. A = rand(4,7);
[M,N] = size(A);
for j = 1:M
for k = 1:N
if A(j,k) < 0.2
A(j,k) = 0;
else
A(j,k) = 1;
end
end
end
3. x = [4 1 6], y = [6 2 7]
N = length(x);
for j = 1:N
c(j) = x(j)*y(j);
for k = 1:N
a(j,k) = x(j)*y(k);
b(j,k) = x(j)/y(k);
d(j,k) = x(j)/(2 + x(j) + y(k));
e(j,k) = 1/min(x(j),y(k));
end
end
c = sum(c);
% or use 1.a. loop
4. These code snippets do the job but their repeated use is much
more interesting. An example is given for the first exercise.
a. total = 0;
% initialize current sum (the test variable)
count = 0;
% initialize the counter (output of the program)
while total < 20
% loop until 20 is exceeded
count = count + 1; % another loop repeat => another number added
x = rand(1,1);
total = total + x; % modify the test variable!
end
disp(['It took ',int2str(count),' numbers this time.'])
-----------------------------------------------------------To do this many times, place the above code in a for-loop.
Some simple (though perhaps subtle) changes are needed wth respect
to retaining the counts for each repeat. Also, the summary has
been changed from a single text message to a histogram.
Nrep = 1000;
% collect 1000 repeats of the above code
count = zeros(Nrep,1);
for j = 1:Nrep
total = 0;
% reset the test variable each repeat!!!
while total < 20
count(j) = count(j) + 1; % use a vector to capture each result
total = total + rand(1,1);
end
end
hist(count,min(count):max(count))
xlabel('Number of random numbers from U(0,1) added to make 20')
ylabel('Count')
title(['Histogram of results for ',int2str(Nrep),' repeats'])
-----------------------------------------------------------b. count = 0;
while 1
% infinite loop use
count = count + 1;
x = rand(1,1);
% get a number
if (x < 0.85) & (x > 0.8)
% check the value
break
% bail out if in selected range
end
end
disp(['It took ',int2str(count),' numbers this time.'])
c. count = 0;
avg = 0;
% test variable
while abs(avg - 0.5) > 0.01
count = count + 1;
%
%
%
%
The following line is one way to update the average.
(count-1)*avg is the sum of the first count-1 numbers
and rand just adds another number. Dividing by count
then gives the new average.
avg = ((count-1)*avg + rand(1,1))/count;
% modify the test var.
% There are other ways to do this and you are encouraged
% to come up with them
end
disp(['It took ',int2str(count),' numbers this time.'])
5. while 1
% use of an infinite loop
TinF = input('Temperature in F: '); % get input
if isempty(TinF)
% how to get out
break
end
TinC = 5*(TinF - 32)/9;
% conversion
disp(' ')
disp([' ==> Temperature in C = ',num2str(TinC)])
disp(' ')
end
IF-block exercises
1. n = 7
gives m = 8
n = 9
gives m = -1
n = -10 gives m = -11
2. z
z
z
z
=
=
=
=
1
9
60
200
gives
gives
gives
gives
w
w
w
w
=
=
=
=
2
0
sqrt(60)
200
3. T = 50 gives h = 0
T = 15 gives h = 31
T = 0 gives h = 1
4. x
x
x
x
=
=
=
=
-1
5
30
100
gives
gives
gives
gives
y
y
y
y
=
=
=
=
-4
20
120
400
Arithmetic:
>> 7+9
>> 3*2
>> 2(3+4)
>> 2+3*4
>> (2+3)*4
>> 2^3
>> 21/7
>> ans*2
>> 3,14
>> 3.14
>> pi
>> 2/3
>> format long
>> 2/3
>> pi
>> round(ans)
>> ceil(3.1)
>> floor(3.1)
>> help
>> help ops
>> helpwin
>> helpdesk
Exercises:
1. Compute the sum of the product of 3 and 4 and the difference between 9 and 3.
2. Convert the binary numbers 10010000 and 1111111111 to the decimal form. Hint: use 2^j.
3. Use helpwin or helpdesk to find a matlab command that does the conversion in previous exercise.
Hint: search for binary.
4. Express pi rounded to 3 decimals. Hint: round 1000*pi.
=================
Variables:
>> a=3
>> b=5; (What is the effect of ; here?)
>> b
>> c=a+2*b;
>> c=c+1
>> c=a*d;
>> base=3
>> height=5
>> area=base*height/2
>> a_minus_b=a-b
>> who
>> whos
>> help who
>> help whos
>> clear
>> who
==================
Vectors/lists:
>> v=[4 1 7 5]
>> v(3)
>> v(3)=8
>> v(5)
>> w=[1 2 3 4]
>> v+w
>> v-w
>> v+1
>> 2*w
>> w/4
>> sum(w)
>> v*w
>> v.*w
>> w.^2
>> [v w]
>> ans'
>> u=1:4
>> u=0:2:10
>> u=0:3:9
>> u=0:3:10
>> u=0:.2:.6
>> u(2:3)
>> help linspace
>> linspace(0,1,6)
Exercises:
1. Define a price list for magazines, movie, cd, and a corresponding list of how many of these items
you consume during a year. Then use these lists to compute a list of the total cost for each of the
three items and the total cost.
2. Test whether 1+2+3+..+N ~= N^2/2 and 1+2^2+3^2+..+N^2 ~= N^3/3. Hint: first define x=1:N
and use sum. What does ~= mean?
======================
Matrices:
>> m=[1 2 3; 4 5 6]
>> m(2,1)
>> m(1,3)
>> m(1,3)=7
>> v
>> w
>> [v;w]
>> v'
>> ans(3)
>> w'
>> [v' w']
>> ans'
>> [v';w']
>> who
>> help save
>> save junk
>> clear
>> who
>> load junk
>> who
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
(type disp('hi') and save file as hello.m)
>> 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)
v=v;
elseif v(2) < v(1)
v=[v(2) v(1)];
end
v
or more elegantly
if v(2) < v(1)
v=[v(2) v(1)];
end
v
and save as MyFirstSort.m. Test the script file with
>> 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
i=i+1;
disp(i)
end
Save as CountToN.m. Test with
>> N=10;
>> CountToN
Alternative code construction
for i=1:N
disp(i)
end
Save as CountToN2.m and test with
>> 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
p=p+1;
r=m-p*n;
end
disp(['m=' num2str(p) 'n+' num2str(r)])
4. Check if a turtle starting at 0 ever reaches 1. Consider and test the following code and explain the
outcome!
pos=0;
while pos<1
step=(1-pos)/2;
pos=pos+step;
disp(pos)
end
5. How would the following code work?
while 1<2
disp('this will go on forever')
end
Try it! If you run into problem you can always press Ctrl-C
6. Try and then seek to understand the following code?
while 1
disp('What is 3+4?')
answer=input('');
if answer == 7
disp('Correct')
return
else
disp('Wrong, but you get another chance.')
end
end
>> help input
============================
Computer arithmetic:
>> eps
(a very small positive number in the computer. The smallest?)
>> eps/2
>> eps/100000000000000
>> help eps
>> 1+eps = = 1
>> 1+eps/2 = = 1
>> a=10
>> a=a^2
(repeat, first until matlab changes to number representation
of the form d.dddde+ddd, and make sure you can interprete this,
then until matlab gets exhausted ..)
>> Inf=Inf+1
>> Inf*2
>> Inf/2
>> 1/eps
>> 1/0
>> -1/0
(seems as if 0 is somewhat positive after all, strange..)
>> 0/0
(Not a Number, without any reasonable interpretation..)
>> 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)
Strings:
>> s=1+2
>> s='1+2'
>> eval(s)
>> f='2*x'
>> eval(f)
>> x=7
>> eval(f)
>> f(2)
>> f(3)
>> ['text1' 'text2']
>> ['text' 7]
>> ['text' num2str(7)]
>> help num2str
>> disp(['f(x)=' num2str(eval(f))])
>> help disp
>> whos
==============================
Elementary graphics:
>> x=0:.2:1
>> y=x.^2
>> plot(x,y)
>> plot(x,1-x/2)
>> plot(x,sin(10*x))
>> x=0:.01:1;
>> plot(x,sin(10*x))
>> xlabel('x')
>> ylabel('y')
>> xlabel('x_1'); ylabel('x_2')
>> title('My first plot')
>> hold on
>> plot(x,x.^2)
>> grid on
>> clf
>> subplot(211); plot(x,sin(10*x))
>> subplot(212); plot(x,x.^2)
>> get(gcf)
============================
Search priorities:
>> max(2,1)
>> max=[1 2 3;4 5 6]
>> max(2,1)
>> clear max
>> max(2,1)
>> hello
( I assume that your hello.m file is intact with the text disp('hi') )
>> hello=5;
>> hello
>> who
>> clear hello
>> hello
>> path
>> help path
>> dir
>> ls
>> help ls
>> help dir
>> help mkdir
>> mkdir m-files
>> help cd
>> cd m-files
>> dir
>> edit
( type disp('hi from hello in m-files') and save as hello.m )
>> hello
>> cd ..
>> hello
(the idea is that you will now get a 'hi' from your old hello.m file)
========================
Documentation:
>> help max
>> edit