Você está na página 1de 7

CMOLER EXERCISES

source: Experiments with MATLAB - CMoler - book


1. INTRO and ITERATIONS
notes: exp(1)=e=2.718281828459046, log(exp(1))=1, log10(10)=1, Loga(x)=logb(x)/loga(b)
lim x(x^n/n^x) lim(ln(x^n)/ln(n^x)) 1/ln(x) 0. pi is not exactly , pi=355/113=3.14159265358979
_______________________________________
1. INTRO and ITERATIONS
format long
q=(1+sqrt(5))/2 = 1.618033988749895
1.1
1.2.a
43^2 = 1849
F = 62
(-3)^4 = 81
C=5/9*(F-32)
sin(1) = 0.841470984807897
C = 16.6667
4^(3^2) =
262144
(-3)^(0.25) = 0.930604859102100 + 0.930604859102099i
1.2.b
sin(pi/180) = 0.017452406437284
C = 100
(4^3)^2 =
4096
F=C*9/5+32
sin(pi/3) = 0.866025403784439
F = 212
(32)^0.25 = 2.378414230005442
(-2)^(-4/3) = -0.198425131496025 + 0.343682409249651i
arcsin(1)/pi = ??? Undefined function or method 'arcsin' for input
arguments of type 'double'.
1.3 pg7 from barn-megaparsec to teaspoon units
1.4
conversion: 1 megaparsec = 0.61742486 teaspoons.
phi=(1+sqrt(5))/2 = 1.618033988749895
x=-1:.025:4;
plot(x,x,'-',x,sqrt(1+x),'-',phi,phi,'o')
Crossing on x=pi .
Improving graph presentation:
set(axes_handle,XGrid,on);
set(axes_handle,YGrid,on); Grid, box, axes, set
1.5 example FOR:
format long
for k=1:31
x=sqrt(1+x)
end
things that can be improved: sqrt(1+x) is evaluated twice
each loop, and comparing R to Z is ok as long as working
floating point as it is the case, otherwise equality may
never be reached regardless of how many loops iterated.

1.6.- example WHILE:


format long
x=3
while x ~= sqrt(1+x)
x = sqrt(1+x)
end
1.7.- PLOT example
phi=(1+sqrt(5))/2
x=-1:.025:4;
plot(x,x,'-',x,sqrt(1+x),'-',phi,phi.'o')

example improved WHILE:


x=3
y = Inf;
while abs(x-y) > eps(x)
y = x;
x = sqrt(1+x)
end

1/7

1.8 sq(x)=x+1 solution, phi, approximated with Taylor series


n=10 % n=10 p/q error < 1.47e-04, n=100 error <e15
p=1;
q=0;
for k=1:n
s=p;
p=p+q;
q=s;
end#p/q
% phi = 1.618033988749895
1.10.- solve sq(x)=x+1

%pick and shovel, then use MATLAB to display result, silly

format long
phi=(1+sqrt(5))/2

10.12.%help fsolve
f = @(x) x-sqrt(1+x)
p = @(x) x^2-x-1
x2 = fsolve(f, 1)
x3 = fsolve(f, -1)
x4 = fsolve(p, 1)
x5 = fsolve(p, -1)
1.14.- % typeset math expressions
format long
pretty(solve('1/x=x-1'))

1.9
% roots
x1 = roots([1 -1 -1])
% fzero
y = tan(x)
z=x
x0=fzero(@(x) tan(x)-x, 4.4)
y0=tan(x0)
x0 = 4.493409457909064
y0 = 4.493409457909065
1.11
look for a zero near x=1:
phi=fzero(f,1)
hold on
plot(phi,0,'+')
1.13
% solve and syms
syms x
x6 = solve('x-sqrt(1+x)=0')
x7 = solve(x^2-x-1)

1.15.- % display 1st component of r vector in variable


% precision format and floating point format
r=solve('1/x=x-1')
vpa(r(1)) %variable precision format

1.16.- r(1)=double(r(1))
% double precision floating point

1.17.- anonymous function: f=@(x) 1./x-(x-1)


ezplot(f,0,4) %quick plot

1.18.- plot a rectangle routine


% GOLDRECT
phi=(1+sqrt(5))/2;
x=[0 phi phi 0 0];
y=[0 0 1 1 0];
u=[1 1];
v=[0 1];
plot(x,y,'b',u,v,'b--')
text(phi/2,1.05,'\phi')
text((1+phi)/2,-.05,'\phi-1')
text(-.05,.5,'1')
text(.5,-.05,'1')
axis equal
axis off
set(gcf,'color','white')

1.19.- function goldfract(n)


%GOLDFRACT Golden ratio continued fraction.
% GOLDFRACT(n) displays n terms.
p = '1';
for k = 1:n
p = ['1+1/(' p ')'];
end
p
p = 1;q = 1;
for k = 1:n
s = p;p = p + q;
q = s;end
p = sprintf('%d/%d',p,q)
format long
p = eval(p)
format short
err = (1+sqrt(5))/2 p

1.20 %sove x=cos(x) within [0 pi/2]


format long
f=@(x) x-cos(x)
q=fzero(f,[-2,2])
x=0:.0025:1.6;
plot(x,x,'-',x,cos(x),'-',q,q,'o')
q

2/7

(1.19) Portugal's flag, golden rectangle: 1/Q=(Q-1)/1

1.21 find 1st 3 zeros starting from x=0 to x=tan(x)


x = pi
while abs(x - tan(x)) > eps(x)
x = atan(x) + pi
end

1.22 %Summation. Write a mathematical expression for


% the quantity approximated
by this program.
s = 0;
t = Inf;
n = 0;
while s ~= t
n = n+1;
t = s;
s = s + 1/n^4;
end

1.23 % copy fixedpoint.m


% slope bouncing approximation example
format short
format long
x = 0;
y = 1;
while x ~= y
delta = y - x;
x = y;
y = sqrt(1 + x);
slope = (y - x)/delta
end

% following 3 lines don't work


for k = 1:30
x = tan(x)
end
1.24

s = 1.082323233710861
n=
9742

%improving plot, example titles axis labels and annotations

%improving plot, example titles axis labels and annotations

x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',5)

(1.24 10 graph points)

1.25
x = -pi:.1:pi;
y = sin(x);
plot(x,y)
set(gca,'XTick',-pi:pi/2:pi)
set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})

(1.24 100 graph points)

3/7

1.26 PLOT y(i,:) multipfunc plot example, Bessel primitive


functions approach
x = [0:.2:20];
y = sin(x)./sqrt(x+1);
y(2,:) = sin(x/2)./sqrt(x+1);
y(3,:) = sin(x/3)./sqrt(x+1);
plot(x,y)

1.27 FPLOT example, huimp and chirp


hmp = @humps;
subplot(2,1,1);fplot(hmp,[0 1])
sn = @(x) sin(1./x);
subplot(2,1,2);fplot(sn,[.01 .1])

1.28 PLOT and AXIS example

1.29

t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi+0.2 pi+0.2 -1.3 1.3])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'{\itNote the odd symmetry.}')

clf;
t = -2*pi:pi/100:2*pi;
x0 = -abs(fzero(@(t) tan(t)-t, -4.4));
y0=tan(x0);x1=fzero(@(t) tan(t)-t, 4.4);
y1=tan(x1);f=tan(t);f(2,:)=t;
plot(t,f,0,0,'o',x0,y0,'o',x1,y1,'o');
axis([-2*pi 2*pi -10 10]);
xlabel('-2\pi \leq {\itt} \leq 2\pi');
ylabel('sin(t)');
title('Graph of the tan function');
text(1,-1/3,'{\it 3 zeros tan(t)-t.}');

1.30 % chirp linear instantaneous frequency deviation

1.31 2 tone f sweep

t = 0:0.001:2;
% 2 secs @ 1kHz sample rate
% Start @ DC, cross 150Hz at t=1 sec
y = chirp(t,0,1,150);
spectrogram(y,256,250,256,1E3,'yaxis')

Fs = 1000;
% Sampling
frequency
T = 1/Fs;
% Sample time
L = 1000;
% Length of
signal
t = (0:L-1)*T;
% Time vector
% Sum of a 50 Hz sinusoid and a 120 Hz
sinusoid
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
y = x + 2*randn(size(t));
% Sinusoids
plus noise
figure(1); plot(Fs*t(1:50),y(1:50))
title('Signal Corrupted with Zero-Mean Random

% chirp quadratic instantaneous freq dev


t = -2:0.001:2; %2 secs @ 1kHz sample rate
% Start @ 100Hz, cross 200Hz at t=1 sec
y = chirp(t,100,1,200,'quadratic');
spectrogram(y,128,120,128,1E3,'yaxis')
t = -1:0.001:1; %+/-1 sec @ 1kHz sample rate
fo = 100; f1 = 400; % convex quad chirp

4/7

% Start at 100Hz, go up to 400Hz


y = chirp(t,fo,1,f1,'q',[],'convex');
spectrogram(y,256,200,256,1000,'yaxis')
t = 0:0.001:10; % 10 sec @ 1kHz sample rate
fo = 10; f1 = 400; % Start 10Hz up to 400Hz
y = chirp(t,fo,10,f1,'logarithmic');
spectrogram(y,256,200,256,1000,'yaxis')

Noise')
xlabel('time (milliseconds)')
NFFT = 2^nextpow2(L); % Next power of 2 from
length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
figure(2); plot(f,2*abs(Y(1:NFFT/2+1)))
title('Single-Sided Amplitude Spectrum of
y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

linear instantaneous frequency deviation

quadratic instantaneous frequency deviation

convex quadratic chirp

logarithmic chirp

5/7

1.32.-

% FIBONACCI Fibonacci sequence


% f = FIBONACCI(n) generates the first n Fibonacci numbers.

n=24;f = zeros(n,1);
1.2. Fibonacci Numbers 9
f(1) = 1;f(2) = 2;for k = 3:n
f(k) = f(k-1) + f(k-2);
end
ans = 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1597 2584 4181 6765 10946 17711 28657 46368
75025
function f = fibnum(n)
%FIBNUM Fibonacci number.
%
FIBNUM(n) generates the n-th Fibonacci
number.
if n <= 1
f = 1;
else
f = fibnum(n-1) + fibnum(n-2);
end

1.33 %zero solving using NR aka 'fixedpoint' iteration


function fixedpoint(f,xmin,xmax,xstart);
% FIXEDPOINT Illustrate fixed point iteration.
% fixedpoint(f,xmin,xmax,xstart) tries to solve x =
f(x).
% Examples
%
f = @(x) sqrt(1+x); fixedpoint(f, -1, 4, 0)
(Default)
%
f = @(x) 1./x+1; fixedpoint(f, .5, 2.5, 1)
%
f = @(x) cos(x); fixedpoint(f, -pi/4, pi/2, 0)
%
a = sqrt(2); f = @(x) a.^x; fixedpoint(f, 1, 5, 3)
%
a = 3+randn, f = @(x) a*x.*(1-x); ...
%
fixedpoint(f, 0, 1, .5), title([num2str(a)
'*x*(1-x)'])

% Default example
if nargin == 0
f = @(x) sqrt(1 + x);
xmin = -1;
xmax = 4;
xstart = 0;
end
% Iteration
x = xstart; y = f(x); n = 1;
while (x(n) ~= y(n)) & (n < 50) &
(max(abs(y)) < 100)
n = n+1;
x(n) = y(n-1);
y(n) = f(x(n));
end
% Plot
t = sort([xmin:(xmax-xmin)/256:xmax x]);
x = [x; x];
y = [x(1) y(1:n-1); y];
plot(t,t,'-',t,f(t),'-',x(:),y(:),'k',x(end),y(end),'ro');
axis tight
axis square
set(zoom(gcf),'ActionPostCallback','zoomer')

1.34

%concave quadratic chirp

t = 0:0.001:1;
% 1 second @ 1kHz sample
rate
fo = 100; f1 = 25;
% Start at 100Hz, go down to
25Hz
y = chirp(t,fo,1,f1,'q',[],'concave');
spectrogram(y,hanning(256),128,256,1000,'yaxis')

% following doesn't work,


x=0:0.05:5;
y=sin(x.^2);
plot(x,y);
xlabel('x')
ylabel('amplitude')

6/7

1.35 contraction: f(x) = sqr(1 + x). For points xn and xn+1 near a fixed point, the function satisfies
abs(yn+1 yn) = abs(f(xn+1) - f(xn)) < *abs( xn+1 xn). This implies that after n steps:
abs(xn+1 xn) < ^n * abs(x1 - x0) . f'(x0), the value of the derivative of f(x) at the fixed point
^10? ^32? fixed point is root to x=sqrt(1+x), since ^n>abs(xn+1-xn)/abs(x1-x0) (f'(x0))^n
x=sqrt(1+x) x0=1.618033988770158
f(x)=sqrt(1+x)) f'(x)=-0.5*(1+x)^(-0.5)
(f'(x0))^10 = 7.940057378387408e-6
(f'(x0))^32 = 4.780085345013851e-17
MSWindows calculator (ver 6.1 build 7600): x=sqrt(1+x) x0=1.618033988770158,
abs(x0-sqrt(1+x0)) = 1.4001493531043385682988887303586e-11
1.36
%LOTKA Lotka-Volterra predator-prey model.
function yp = lotka(t,y)
global ALPHA BETA
yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];
% ALPHA = BETA = 0.1 race mode

%file lotka2.m
global ALPHA BETA
ALPHA = 0.01
BETA = 0.03
[t,y] = ode23(@lotka,[0,10],[1; 1]);
plot(t,y);
% ALPHA = 1, BETA = 0.03 persecution mode

% ALPHA = BETA = 0.4 , combat mode


global ALPHA BETA
ALPHA = 0.4
BETA = 0.4
[t,y] = ode23(@lotka,[0,10],[1; 1]);
plot(t,y);

7/7

Você também pode gostar