Você está na página 1de 13

John Bofarull Guix attached: -- 1 / 13

MATLAB - CMOLER 2.- FIBONACCI


source: Experiments with MATLAB - CMoler - book
CONTENTS

Exercises: 2.1 to 2.8

Fourier square pulse train example
MATLAB as automation server
Kronecker Tensor Product
Linear data regression example and literature examples
Vectorizing code

in NOTES: slash and back slash operators
spotted printout error on ch2 pg4.
spotted execution time not exactly same on same repeated operation
fibnum delays calculated up to 24th iteration


EXERCISES

2.1 Walsh, f(n) even when n=3*k-1, k>=1
why? taking into account the four basic rules odd(any) + odd (any) = even, odd +even or even+ odd is odd, even+ even is even,
and that f(0)=1 odd, f(1)=1 odd, then f(3) even, f(4) odd, f(5) odd and f(5) even again. This cycle happens for any n, as long as
starting on two consecutive odds.

2.2 Backslash
c1 + c2 = 1;
c1 * phi + c2 * phi = 1
X = 0.723606797749979
0.276393202250021
help \
Arithmetic operators.
plus - Plus +
uplus - Unary plus +
minus - Minus -
uminus - Unary minus -
mtimes - Matrix multiply *
times - Array multiply .*
mpower - Matrix power ^
power - Array power .^
mldivide - Backslash or left matrix divide \
mrdivide - Slash or right matrix divide /
ldivide - Left array divide .\
rdivide - Right array divide ./
kron - Kronecker tensor product kron
Relational operators.
eq - Equal ==
ne - Not equal ~=
lt - Less than <
gt - Greater than >
le - Less than or equal <=
ge - Greater than or equal >=
Logical operators.
relop - Short-circuit logical AND &&
relop - Short-circuit logical OR ||
and - Element-wise logical AND &
or - Element-wise logical OR |
not - Logical NOT ~
xor - Logical EXCLUSIVE OR
any - True if any element of vector is nonzero
all - True if all elements of vector are nonzero
Special characters.
colon - Colon :
paren - Parentheses and subscripting ( )
paren - Brackets [ ]
paren - Braces and subscripting { }
punct - Function handle creation @
punct - Decimal point .
punct - Structure field access .
punct - Parent directory ..
punct - Continuation ...
punct - Separator ,
punct - Semicolon ;
punct - Comment %
punct - Invoke operating system command !
punct - Assignment =
help slash
Matrix division.
\ Backslash or left division.
A\B is the matrix division of A into B, which is roughly the
same as INV(A)*B , except it is computed in a different way.
If A is an N-by-N matrix and B is a column vector with N
components, or a matrix with several such columns, then
X = A\B is the solution to the equation A*X = B computed by
Gaussian elimination. A warning message is printed if A is
badly scaled or nearly singular. A\EYE(SIZE(A)) produces the
inverse of A.

If A is an M-by-N matrix with M < or > N and B is a column
vector with M components, or a matrix with several such columns,
then X = A\B is the solution in the least squares sense to the
under- or overdetermined system of equations A*X = B. The
effective rank, K, of A is determined from the QR decomposition
with pivoting. A solution X is computed which has at most K
nonzero components per column. If K < N this will usually not
be the same solution as PINV(A)*B. A\EYE(SIZE(A)) produces a
generalized inverse of A.

/ Slash or right division.
B/A is the matrix division of A into B, which is roughly the
same as B*INV(A) , except it is computed in a different way.
More precisely, B/A = (A'\B')'. See \.

./ Array right division.
B./A denotes element-by-element division. A and B
must have the same dimensions unless one is a scalar.
A scalar can be divided with anything.
.\ Array left division.
A.\B. denotes element-by-element division. A and B
must have the same dimensions unless one is a scalar.
A scalar can be divided with anything.
Bitwise operators.
bitand - Bit-wise AND.
bitcmp - Complement bits.
bitor - Bit-wise OR.
bitmax - Maximum floating point integer.
bitxor - Bit-wise XOR.
bitset - Set bit.
bitget - Get bit.

John Bofarull Guix attached: -- 2 / 13
punct - Quote '
transpose - Transpose .'
ctranspose - Complex conjugate transpose '
horzcat - Horizontal concatenation [,]
vertcat - Vertical concatenation [;]
subsasgn - Subscripted assignment ( ),{ },.
subsref - Subscripted reference ( ),{ },.
subsindex - Subscript index
metaclass - Metaclass for MATLAB class ?

bitshift - Bit-wise shift.
Set operators.
union - Set union.
unique - Set unique.
intersect - Set intersection.
setdiff - Set difference.
setxor - Set exclusive-or.
ismember - True for set member.
See also arith, relop, slash, function_handle.
2.3 logarithmic plot. semilogy(fibonacci(18),'o-')

2.4 execution time of fibnum(n-1) and fibnum(n-2)
(note 3: Q: why execution time is not constant for same
command order? )
for k=1:1:15 tic; fibnum(k); disp(fibnum(k)); toc; end
1 Elapsed time is 0.000950 seconds.
2 Elapsed time is 0.000616 seconds.
3 Elapsed time is 0.000418 seconds.
5 Elapsed time is 0.000718 seconds.
8 Elapsed time is 0.001062 seconds.
13 Elapsed time is 0.001692 seconds.
21 Elapsed time is 0.002687 seconds.
34 Elapsed time is 0.005033 seconds.
55 Elapsed time is 0.006815 seconds.
89 Elapsed time is 0.013397 seconds.
144 Elapsed time is 0.019703 seconds.
233 Elapsed time is 0.036617 seconds.
377 Elapsed time is 0.052666 seconds.
610 Elapsed time is 0.080884 seconds.
987 Elapsed time is 0.127804 seconds.
2.4 n=15;
%estimate execution time
for k=1:1:n tic; fibnum(k);
disp(fibnum(k)); t(k)=toc; end
p=1:n; plot(p,1+10*t,'o')

notes 3, 4, 5.
2.4 fibnum(n) execution time as function of fibnum(n-1) and
fibnum(n-2) execution times: multiply times. exp(n)
n=24;
for k=1:1:n tic; fibnum(k); disp(fibnum(k));
t(k)=toc; end
p=1:n
plot(p,1+10*t,'o')

n=24; %scattered data
for k=1:1:n tic; fibnum(k); disp(fibnum(k));
t(k)=toc; end
p=1:n
plot(p,1+10*t,'o')
% ordinary least square regression
%bls=regress(1+10*t,[ones(10,1) p])
%robust regression
brob=robustfit(p,1+10*t)

scatter(p,1+10*t,'filled'); grid on; hold on
%plot(p,bls(1)+bls(2)*p,'r','LineWidth',2);
plot(p,brob(1)+brob(2)*p,'g','LineWidth',2)
legend('Data','Ordinary Least Squares','Robust
Regression')


John Bofarull Guix attached: -- 3 / 13

2.4.1 first approach (wrong)
not finding exp based specific regress function, took all 24 samples to Excel and '=FORECAST(50,known y's, known x's)'
(known x's the counter 1, 2, .. 50 known y's are t(k)=toc, using samples 21 to 24 only, E<p(50)>= 35.49233636
then, there are three areas to sum: 1.- area under forecast line between (24, 4.779sec) to (Excel Forecast function: 50,
35.4sec), (35.4+4.779)/2 * 25 = 502.237 2.- square under previous area, square 4.779sec*(50-24+1)= 119.475 , and
3.- time from iterations 0 to 24; 1.844sec: 502.237 + 119.475 + 1.844 = 623.55sec = 10min23sec, approx 11 minutes.
4min past expected delay and just began calculating last iteration, which will take probably longer than 5minutes, so the
overall error estimating p(50> with a line using p on points 21..24 is not a reliable way to estimate exponentials.
started at 20h46', now 22h00' (over 1h13') and MATLAB still busy.

2.4.2 read the manual! quick look to n = (1:40)';f = round((phi.^(n+1) - (1-phi).^(n+1))/(2*phi-1)),
f(n large enough) = phi^(n+1) shows up 369929706.85777 - 2.6948058e-9/2.236 369929706.85
the same applies for n=(1:50), f phi.^(n+1) fibnum(50) phi^(50+1) = 45488789614.679
then 3.- time from iterations 0 to 24: 1.844sec, 2.- box under estimated area: 4.779sec*(50-24+1)= 119.475, and 1.-
half area in square (24, 4.779) (50, 45488789614.68) : 1137219740247.525sec , <315million hours (!?)

2.4.3.- Do not use 'too long' segments to estimate exponential and log functions. Take 3 points and use an exponential
function instead of lines. (12, 0.02609) (24, 4.779) (50, 45488789614.6798), y=C*exp(a*x)+K , (y-K )/C=exp(a*x), ln((y-
K)/C)=a*x, ln(y-K) ln(C)=a*x
Q: ln(y1-K)-ln(C)=a*x1, [[ ln(y1- ) -ln( ) -x1] [[K] [[0] and solve, Cramer? A: No, ln(a+b) is not a linear
ln(y2-K)-ln(C)=a*x2, [ln(y2- ) -ln( ) -x2] X [C] = [0] operator, ln(ln(A)+B) is not
ln(y3-K)-ln(C)=a*x3 [ln(y3- ) -ln( ) -x3]] [a]] [0]] ln(ln(A+B))
help: goalattain, Optimization Toolbox : fminimax
min{f1(K,C,a),f2(K,C,a),f3(K,C,a)}
x0=[1;1;1]
% options=optimset('MinAbsMax',5); to work with absolute values
options=optimset('MinAbsMax',1);
[x,fval]=fminimax(@q,x0)

Optimization terminated: directional derivative predicts change in objective
value less than options.TolFun and maximum constraint violation is less than
options.TolCon.
No active inequalities.
x = 9.899738431220481 -10.099999975977370
1.999997117284377
fval = 1.0e+010 * Columns 1 through 2
-0.000000002402263 -0.000000004867917
Column 3 -9.097744809673623 - 0.000000000314159i
support file q.m
%auxiliary function to fminimax
% (12, 0.02609) (24, 4.779) (50, 45488789614.6798),
% y=C*exp(a*x)+K ,
% (K-y )/C=exp(-a*x), ln((K-y)/C)=-a*x, ln(K-y)
ln(C)=-a*x

function f=q(x)
f(1)=log(x(1)-0.02609)-log(x(2))+x(3)*12;
f(2)=log(x(1)-4.779)-log(x(2))+x(3)*24;
f(3)=log(x(1)-50)-
log(x(2))+x(3)*45488789614.6798;
format long;

2.4.4 over dimensioned; reduce number of equations to 2 only or peak and shovel; find K a C manually.
manual mode : K0 because initial delays are nearly zero. exp(a*(x-b)) better than exp(a*x), K removed but adding b.
peakandshovel.m
%f=@(t.) C*exp(a*(t-b))+K;
t = 1:1:50;
x1=24.000000001;y1=4.779;
x0=12.000000001;y0=0.02609;
x2=32;y2=95.5659;
f=0.6*exp(0.44*t-9);f(2,:)=100*t;
semilogy(t,f,0,0,'o',x0,y0,'o',x1,y1,'o',x2,y2,'o');
axis(tight);
xlabel('0 to 50');
ylabel('C*exp(a*(t-b))');
title('Graph of an exp function');
text(1,-1/3,'{\it 3 zeros tan(t)-t.}');


delay approximated with function f=0.6*exp(0.44*t-9)= 265448.0352'' = 73h44', less than 74 hours

John Bofarull Guix attached: -- 4 / 13
2.5 overflow. What is the index of the largest Fibonacci number that can be represented exactly as a Matlab double-
precision quantity without roundoff error?
it is the Fibonacci number closest to intmax('uint64') = ffffffff ffffffff = 18446744073709551615 = phi^(n+1)
n=(log(18446744073709551615)-log(phi))/log(phi)=91.18
rounding down to int, answer is n= 91.
What is the index of the largest Fibonacci number that can be represented approximately as a Matlab double-precision
quantity without overflowing?

overflow variables, overload operators
format short 3.1516 format long 3.14159265358979
format short e 3.1416e+000 format long e 3.14159265358979e+000
format short g 3.1416 format long g 3.14159265358979
format hex 400921fb54442d18 format bank 3.14
format + + format rat 355/113
fixed point representation: real value=2^-(fraction length)* stored integer = (slope * stored integer) + bias.
Inside the Fixed Point Tool Box: fi() constructs a fi object which has 3 general types of properties: Data, fimath and
numeric type Properties. format hex
realmax ans = 7fefffffffffffff; realmin ans = 0010000000000000
format long realmax ans = 1.797693134862316e+308; realmin ans = 2.225073858507201e-308

2.6 slower maturity. Table comparing 24 terms of both fibonacci and fibonacci slow maturity series
2.6.a
% f(n)=f(n-1)+f(n-3)
function f = t28fibonacci(n)
f = zeros(n,1);
f(1) = 1; f(2)=1;f(3) = 2;
for k = 4:n
f(k) = f(k-1) + f(k-3); end
1 1 0 13 9 4 233 88 145 4181 828 3353
1 1 0 21 13 8 377 129 248 6765 1278 5487
2 2 0 34 19 16 610 189 421 10946 1873 9073
3 3 0 55 28 27 987 277 710 17711 2745 14966
5 4 1 89 41 58 1597 406 1191 28657 4023 24634
8 6 2 144 60 84 2584 595 1989 46368 5896 40472
observation: a tiny reproductive delay of a single unit on clock cycle number 5, and on cycle 24 the
group/team/town/country that has suffered such early delay is 12% of the on time group.
2.6.b In 12 months there are 72 pairs of rabbits.
2.6.c g(n)c*^n; g(n)=g(n-1)+g(n-3), ^3= ^2 +1 ; x1= roots([1 -1 0 -1]); 1.465571231876768
(since real axis is considered only the other 2 solutions are not relevant now -0.2327 + 0.7925i, -0.2327 - 0.7925i)
lim(n) g(n)/g(n-1)= = 1.465571231876768 . and look like birth rates.
function f = fib3(n)
% FIBONACCI MODIFIED Fibonacci sequence with slower maturity
format long;
f=zeros(n,1);
f(1)=1;
f(2)=1;
f(3)=2;
for k = 4:1:n
f(k) = f(k-1) + f(k-3);
end

ALSO

% FIBNUM2(n) generates the nth Fibonacci slower maturity number.
function f = fibnum2(n)
if n <= 2
f = 1;
else
f = fibnum2(n-1) + fibnum2(n-3);
end

fib3(63) % computing in g(n)c*^n
ans = 1.000000000000000
1.000000000000000
2.000000000000000
1.500000000000000
1.333333333333333
1.500000000000000
1.500000000000000
1.444444444444444
1.461538461538462
1.473684210526316
1.464285714285714
1.463414634146341
1.466666666666667
1.465909090909091
1.465116279069767

1.465571231876768
1.465571231876770
1.465571231876768
1.465571231876768 =
note 7: accuracy problem when using early fib3(n)






John Bofarull Guix attached: -- 5 / 13
2.6.d % tictoconfibnum2(n)
n=14; for k=1:1:n tic; fibnum2(k);
disp(fibnum2(k));
m(k)=toc; end
p=1:n; disp(m); s=0;
for j=1:1:n s=m(j)+s; end
disp(s);

for 32 terms for fibonacci slow maturity series total delay
10.9390sec , again manual mode, taking 3 points:
(12,0.0017861) (24,0.159265) (32,3.5043589)
after some iterations f=0.6*exp(0.386*t-9)/5;
answer 3567.91426'' = 59min28''

%peakandshovel2.m
%f=@(t.) C*exp(a*(t-b))+K;
t = 1:1:50;
x1=24.000000001;y1=0.159265;
x0=12.000000001;y0=0.0017861;
x2=32;y2=3.5043589;
f=0.6*exp(0.386*t-9)/5;f(2,:)=100*t;
semilogy(t,f,0,0,'o',x0,y0,'o',x1,y1,'o',x2,y2,'o');
axis(tight);
xlabel('0 to 50');
ylabel('C*exp(a*(t-b))');
title('Graph of an exp function');
text(1,-1/3,'{\it 3 zeros tan(t)-t.}');




2.7 mortality rate. d1=1, d2=1, d(n)=d(n-1)+d(n-2)-d(n-
7)
2.7.a compute sequence and fibnum
2.7.b how many pairs of rabbits after 12 months?
101 pairs and 1 unit.
2.7.c d(n) ^n, ? d(n)c* ^n;
g(n)=g(n-1)+g(n-3), ^7= ^6+ ^5 +1 ; x1=
roots([1 -1 -1 0 0 0 0 -1]); = 1.653634586774047
0.724 + 0.5634i 0.724 - 0.5634i -0.887 + 0.3823i -
0.887 - 0.3823i -0.163 + 0.8616i -0.163 - 0.8616i


1. 1
2. 2
3. 3
4. 5
5. 8
6. 13
7. 21
8. 33
9. 52
10. 82
11. 129
12. 203

13. 319
14. 501
15. 787
16. 1236
17. 1941
18. 3048
19. 4786
20. 7515
21. 11800
22. 18528
23. 29092
24. 45679
2.7.a function f = fib27(n)
% FIBONACCI modified sequence
% f = FIB27(n) generates the first n Fibonacci numbers.
f = zeros(n,1); f(1) = 1;f(2) = 2;f(3) = 3;f(4) = 5;f(5) =
8;f(6) = 13; f(7) = 21;
for k = 8:1:n
f(k) = f(k-1) + f(k-2)-f(k-7);
end

2.7.a function f = fibnm3(n)
% FIBNUM modified number.
% FIBNM3(n) generates the nth Fibonacci number.
if n <= 1
f = 1; elseif (n==2) f=2; elseif (n==3) f=3; elseif (n==4)
f=5; elseif (n==5) f=8; elseif (n==6) f=13; elseif (n==7)
f=21;
else
f = fibnm3(n-1) + fibnm3(n-2)-fibnm3(n-7);
end
%peakandshovel2.m
%f=@(t.) C*exp(a*(t-b))+K;
t = 1:1:50;
x1=24.000000001;y1=0.159265;
x0=12.000000001;y0=0.0017861;
x2=32;y2=3.5043589;
f=0.6*exp(0.386*t-9)/5;f(2,:)=100*t;
semilogy(t,f,0,0,'o',x0,y0,'o',x1,y1,'o',x2,y2,'o');
axis(tight);
xlabel('0 to 50');
ylabel('C*exp(a*(t-b))');
title('Graph of an exp function');
text(1,-1/3,'{\it 3 zeros tan(t)-t.}');




John Bofarull Guix attached: -- 6 / 13
2.6.d % tictoconfibnm3(n)
n=32; for k=1:1:n tic; fibnm3(k); disp(fibnm3(k));
m(k)=toc; end
p=1:n; disp(m); s=0;
for j=1:1:n s=m(j)+s; end
disp(s);

for 32 terms for fibonacci series total delay , again
manual mode, taking 3 points:
(12, 0.00230) (24,0.977139) (32, 56.811253)

after some iterations f=0.4*exp(0.506*t-9)/8;
answer = 599749.7275'' = 166h36'

%peakandshovel3.m
%f=@(t.) C*exp(a*(t-b))+K;
t = 1:1:50;
x1=24.000000001;y1=0.977139;
x0=12.000000001;y0=0.0023;
x2=32;y2=58.811253;
f=0.4*exp(0.506*t-9)/8;f(2,:)=100*t;
semilogy(t,f,0,0,'o',x0,y0,'o',x1,y1,'o',x2,y2,'o');
axis(tight);
xlabel('0 to 50');
ylabel('C*exp(a*(t-b))');
title('Graph of an exp function');
text(1,-1/3,'{\it 3 zeros tan(t)-t.}');
1. 0.00225
2. 0.00106
3. 0.00016
4. 0.00012
5. 0.00013
6. 0.00013
7. 0.00013
8. 0.00054
9. 0.00047
10. 0.00078
11. 0.00147
12. 0.00230
13. 0.00409
14. 0.006668
15. 0.010941
16. 0.017418
17. 0.028435
18. 0.049171
19. 0.084541
20. 0.150144
21. 0.216092
22. 0.346548
23. 0.571955
24. 0.977139
25. 1.7850926
26. 2.6911010
27. 4.4040258
28. 7.3607346
29. 13.456511
30. 20.103730
31. 33.855057
32. 56.811253

total:
142.9402sec


2.8 MATLAB Graphics Handles. Fibonacci's rabbit pen
function rabbits(action)
% RABBITS Fibonacci's rabbit pen.
% Create immature pushbuttons that age after one click.

if nargin == 0
clf reset
shg
uicontrol('style','text','fontsize',12,'fontweight','bold', ...
'units','normal','position',[.47 .94 .06 .04])
R = imread('rabbit.jpg');
set(gcf,'userdata',R);
action = 'mature';
end

R = get(gcf,'userdata');
switch action
case 'immature'
p = get(gcbo,'position');
p = [p(1:2)-15 60 60];
c = 'rabbits(''mature'')';
set(gcbo,'cdata',R,'position',p,'callback',c,'enable','off');
case 'mature'
f = get(gcf,'position');
p = [.90*f(3:4).*rand(1,2) 30 30];
c = 'rabbits(''immature'')';
r = R(1:2:end,1:2:end,:);
uicontrol('style','pushbutton','position',p,...
'cdata',r,'callback',c,'enable','off')
if nargin > 0
set(gcbo,'enable','off')
end
end

b = findobj(gcf,'style','pushbutton');
if ~any(any(char(get(b,'enable')) == 'n'))
set(b,'background','w','enable','on')
end
set(findobj(gcf,'style','text'),'string',length(b))







John Bofarull Guix attached: -- 7 / 13
2.9.1
%function fibonacci no parameters
n=25;
f = zeros(n,1);
f(1) = 1;f(2) = 2;
for k = 3:n
f(k) = f(k-1) + f(k-2);
end
disp(f);


2.10 function fourier_demo
t = 0:.1:pi*4;
y = sin(t);
updatePlot(t,y);

% In each iteration of the for loop add an odd
% harmonic to y. As "k" increases, the output
% approximates a square wave with increasing accuracy.
for k = 3:2:9
% Perform the following mathematical operation
% at each iteration:
y = y + sin(k*t)/k;
display(sprintf('When k = %.1f',k));
display('Then the plot is:');
updatePlot (t,y)
end
end

% Even though the approximations are constantly
% improving, they will never be exact because of the
% Gibbs phenomenon, or ringing.
function updatePlot(t,x)
% Subfunction to update the plot
cla
plot(t,x)
end

2.11
% FIBNUM Fibonacci number.
% FIBNUM(n) generates the nth Fibonacci number.
function f = fibnum(n)
if n <= 1
f = 1;
else
f = fibnum(n-1) + fibnum(n-2);
end

fibnum(4)
ans = 5
fibnum(12)
ans = 233

2.12 measuring execution time: tic, fibnum(n), toc

tic, fibnum(12), toc; ans = 233; Elapsed time is 0.017673 seconds.
tic, fibnum(24), toc; ans = 75025; Elapsed time is 5.307945 seconds.
tic, fibnum(24), toc; ans = 75025; Elapsed time is 5.271380 seconds.
tic, fibnum(30), toc; ans = 1346269; Elapsed time is 94.070002 seconds.

apparently execution time is not constant, fibnum(12) differed 0.036565sec

queries like help fibonacci or help fibnum return the contents of both comment lines


2.13 (1
st
time) Start > MATLAB > Notebook, then MATLAB launches MSWord
Welcome to the utility for setting up the MATLAB Notebook
for interfacing MATLAB to Microsoft Word

Setup complete Warning: MATLAB is now an automation server








John Bofarull Guix attached: -- 8 / 13
2.14
function f=goldfract(n)
%GOLDFRACT Golden ratio continued fraction.
%GOLDFRACT(n) displays n terms.
%assert(isa(n,'double'));
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
f = eval(p)

format short
err = (1+sqrt(5))/2 - p
disp(f);
disp(err);
2.15
n=40
fibonacci(n)
f(2:n)./f(1:n-1)
f(2:n)/f(1:n-1)
f(n)/f(n-1)

%phi(n)=f(n+1)/f(n)
phi= q=(1+sqrt(5))/2 = 1.618033988749895

f(n)/f(n-1)-phi = 0

closed form solution to Fibonacci recurrence relation:
f(n)=f(n-1)+f(n-2)

f(n)=c*^n
for some c and f(n)=f(n-1)+f(n-2) becomes
^2= +1
general solution to fibonacci recurrence:
f(n)= c1*phi^n+c2*(1-phi)^n
initial conditions:
f(0)=c1+c2=1, f(1)=c1*phi+c2*(1-phi)=1
n=(1:40)'
f=round((phi.^(n+1)-(1-phi).^(n+1))/(2*phi-1))

2.16 Kronecker Tensor Product
The Kronecker product, kron(X,Y), of two matrices is the larger matrix formed from all possible products of the elements of X with
those of Y. If X is m-by-n and Y is p-by-q, then kron(X,Y) is mp-by-nq. The elements are arranged in the following order:
[X(1,1)*Y X(1,2)*Y . . . X(1,n)*Y
. . .
X(m,1)*Y X(m,2)*Y . . . X(m,n)*Y]
The Kronecker product is often used with matrices of zeros and ones to build up repeated copies of small matrices. For example, if X is
the 2-by-2 matrix
X = 1 2
3 4
and I = eye(2,2) is the 2-by-2 identity matrix, then the two matrices kron(X,I)and kron(I,X) are
1 0 2 0
0 1 0 2
3 0 4 0
0 3 0 4 and

1 2 0 0
3 4 0 0
0 0 1 2
0 0 3 4
2.17 LINEAR DATA REGRESSION EXAMPLE

%Generate data with the trend y = 10-2*x, then change one value to
%simulate an outlier:
x = (1:10)';
y = 10 - 2*x + randn(10,1);
y(10) = 0;
%Use both ordinary least squares and robust regression to estimate a
%straight-line fit:
bls = regress(y,[ones(10,1) x])
bls = 7.2481
-1.3208
brob = robustfit(x,y)
brob = 9.1063
-1.8231
%A scatter plot of the data together with the fits shows that the robust fit
%is less influenced by the outlier than the least-squares fit:
scatter(x,y,'filled'); grid on; hold on
plot(x,bls(1)+bls(2)*x,'r','LineWidth',2);
plot(x,brob(1)+brob(2)*x,'g','LineWidth',2)
legend('Data','Ordinary Least Squares','Robust Regression')



John Bofarull Guix attached: -- 9 / 13
Data Regression Literature References

[1] DuMouchel, W. H., and F. L. O'Brien. "Integrating a Robust Option into a Multiple Regression Computing
Environment." Computer Science and Statistics: Proceedings of the 21st Symposium on the Interface. Alexandria, VA:
American Statistical Association, 1989.
[2] Holland, P. W., and R. E. Welsch. "Robust Regression Using Iteratively Reweighted Least-Squares." Communications
in Statistics: Theory and Methods, A6, 1977, pp. 813827.
[3] Huber, P. J. Robust Statistics. Hoboken, NJ: John Wiley & Sons, Inc., 1981.
[4] Street, J. O., R. J. Carroll, and D. Ruppert. "A Note on Computing Robust Regression Estimates via Iteratively
Reweighted Least Squares." The American Statistician. Vol. 42, 1988, pp. 152154.

2.18 Vectorizing code
for i=1:n; y)i_=sin(2*pi*i/m); vectorized: i=1:n; y=sin(2*pi*i/m);

2.19 EXCEL IO
% exporting data to MSExcel spreadsheet
%d = 'Time' 'Temp'
% [ 12] [ 98]
% [ 13] [ 99]
% [ 14] [ 97]
d = {'Time', 'Temp'; 12 98; 13 99; 14 97}
xlswrite('C:\ .. \MATLAB exercises\datain.xlsx', d, 'Temperatures', 'E1');


note 1:
slash and backslash operators:
The two division symbols, slash, /, and backslash, \, correspond to the two MATLAB functions mldivide and mrdivide.
mldivide and mrdivide are used for the two situations where the unknown matrix appears on the left or right of the
coefficient matrix:
X = B/A Denotes the solution to the matrix equation XA = B.
X = A\B Denotes the solution to the matrix equation AX = B.
Think of "dividing" both sides of the equation AX = B or XA = B by A. The coefficient matrix A is always in the
"denominator."
The dimension compatibility conditions for X = A\B require the two matrices A and B to have the same number of rows.
The solution X then has the same number of columns as B and its row dimension is equal to the column dimension of A.
For X = B/A, the roles of rows and columns are interchanged.
In practice, linear equations of the form AX = B occur more frequently than those of the form XA = B. Consequently, the
backslash is used far more frequently than the slash. The remainder of this section concentrates on the backslash
operator; the corresponding properties of the slash operator can be inferred from the identity:
(B/A)' = (A'\B')
The coefficient matrix A need not be square. If A is m-by-n, there are three cases:
m = n Square system. Seek an exact solution.
m > n Over determined system. Find a least squares solution.
m < n Underdetermined system. Find a basic solution with at most m nonzero components.
The mldivide Algorithm
The mldivide operator employs different algorithms to handle different kinds of coefficient matrices. The various cases
are diagnosed automatically by examining the coefficient matrix.
Permutations of Triangular Matrices
mldivide checks for triangularity by testing for zero elements. If a matrix A is triangular, MATLAB software uses a
substitution to compute the solution vector x. If A is a permutation of a triangular matrix, MATLAB software uses a
permuted substitution algorithm.
Square Matrices
If A is symmetric and has real, positive diagonal elements, MATLAB attempts a Cholesky factorization. If the Cholesky
factorization fails, MATLAB performs a symmetric, indefinite factorization. If A is upper Hessenberg, MATLAB uses
Gaussian elimination to reduce the system to a triangular matrix. If A is square but is neither permuted triangular,
symmetric and positive definite, or Hessenberg, MATLAB performs a general triangular factorization using LU factorization
with partial pivoting (see lu).
Rectangular Matrices
If A is rectangular, mldivide returns a least-squares solution. MATLAB solves overdetermined systems with QR
factorization (see qr). For an underdetermined system, MATLAB returns the solution with the maximum number of zero
elements.

John Bofarull Guix attached: -- 10 / 13
The mldivide function reference page contains a more detailed description of the algorithm.
linear equations systems: AX = 0. Solve this using the null command, by typing null(A).
AX = b , example
A = pascal(3);
u = [3; 1; 4];
x = A\u
x = 10
-12
5
note 2: printing error CMOLER exercises ch2 pg4. Where one reads;
'Now compare the results produced by goldfract(6) and fibonacci(7)..'
it should be 'Now compare the results produced by goldfract(6) and Fibonacci(6)/fibonacci(7)..'
note 3: Q: why execution time is not constant for same
command order? example
tic; fibnum(10); toc;
Elapsed time is 0.007717 seconds.
for k=1:1:15 tic; fibnum(10); toc; end
Elapsed time is 0.007162 seconds.
Elapsed time is 0.006066 seconds.
Elapsed time is 0.005433 seconds.
Elapsed time is 0.005258 seconds.
Elapsed time is 0.008063 seconds.
Elapsed time is 0.005963 seconds.
Elapsed time is 0.010779 seconds.
Elapsed time is 0.005368 seconds.
Elapsed time is 0.008680 seconds.
Elapsed time is 0.005517 seconds.
Elapsed time is 0.009052 seconds.
Elapsed time is 0.005494 seconds.
Elapsed time is 0.005331 seconds.
Elapsed time is 0.008489 seconds.
Elapsed time is 0.005525 seconds.

note 4: delays up to 24 iterations
1. 0.001964285622630
2. 2.237858718230490e-004
3. 2.694669328144512e-004
4. 2.766527176895033e-004
5. 4.244745779762879e-004
6. 7.103661619337153e-004
7. 0.001199512803785
8. 0.002190124575846
9. 0.003450716551070
10. 0.005384205952807
11. 0.010020577008260
12. 0.026090558340617
13. 0.042760552710042
14. 0.039415056580357
15. 0.070929342690594
16. 0.103922360674047
17. 0.157773145798035
18. 0.254799719343774
19. 0.414208144471231
20. 0.708929518229053
21. 1.227944388184311
22. 1.843335004883767
23. 3.098461677439356
24. 4.779863993623129
fibonacci n=32:
1. 1
2. 2
3. 3
4. 5
5. 8
6. 13
7. 21
8. 34
9. 55
10. 89
11. 144
12. 233
13. 377
14. 610
15. 987
16. 1597
17. 2584
18. 4181
19. 6765
20. 10946
21. 17711
22. 28657
23. 46368
24. 75025
25. 121393
26. 196418
27. 317811
fibnum execution delays up to n=32
1. 0.000694968051487
2. 0.000410616278574
3. 0.000116512369045
4. 0.000165273052126
5. 0.000262281147939
6. 0.000451677906432
7. 0.000705233458452
8. 0.001190787207866
9. 0.001960692730193
10. 0.003320859152970
11. 0.007342845601607
12. 0.008868285076511
13. 0.011747218459665
14. 0.017929559803951
15. 0.028440823265108
16. 0.045343842372623
17. 0.073724613006989
18. 0.118226692008535
19. 0.190135867793877
20. 0.315846554749778
21. 0.493183513140491
22. 0.792871290787670
23. 1.253353323502495
24. 2.005175304921082
25. 3.212390243551913
26. 5.198782933350305
27. 8.533724684864838

John Bofarull Guix attached: -- 11 / 13
28. 514229
29. 832040
30. 1346269
31. 2178309
32. 3524578

28. 13.896964570487674
29. 22.721915258038969
30. 36.939981245101478
31. 59.548222519120607
32. 95.565903656076017
total delay: 2.509893537464373e+002 = 4'10''

note 5: attempt with fminimax, garbage
x = 1.0e+006 * -6.670022604111678 5.026012786066976 8.470236601951457
fval = 1.0e+017 * -0.000000001016428 -0.000000002032857 -3.853008107727302

options=optimset('MinAbsMax',100);
x0=[10;-10;10]
x = 9.899738431220481 -10.099999975977370 1.999997117284377
fval = 1.0e+010 * Columns 1 through 2
-0.000000002402263 -0.000000004867917
Column 3 -9.097744809673623 - 0.000000000314159i

x0=[24;48;-10]
x = 1.0e+007 * -0.012746484169181 0.006355841042157 3.661172592962217
fval = 1.0e+018 * -0.000000000439341 -0.000000000878681 -1.665423098242900

note 6: Fixed Point Tool Box
Fixed-Point Toolbox software provides fixed-point data types in MATLAB

technical computing software


and enables algorithm development by providing fixed-point arithmetic. The toolbox enables you to create the
following types of objects:
fi Defines a fixed-point numeric object in the MATLAB workspace. Each fi object is composed of
value data, a fimath object, and a numerictype object.
fimath Governs how overloaded arithmetic operators work with fi objects
fipref Defines the display, logging, and data type override preferences of fi objects
numerictype Defines the data type and scaling attributes of fi objects
quantizer Quantizes data sets
Fixed-Point Toolbox software provides you with
The ability to define fixed-point data types, scaling, and rounding and overflow methods in the
MATLAB workspace
Bit-true real and complex simulation
Basic fixed-point arithmetic
o Arithmetic operators +, -, *, .* for binary point-only and real [Slope Bias] signals
o Division using the divide function for binary point-only signals
Arbitrary word length up to intmax('uint16') bits
Logging of minimums, maximums, overflows, and underflows
Data type override with singles, doubles, or scaled doubles
Conversions between binary, hex, double, and built-in integers
Relational, logical, and bitwise operators
Matrix functions such as ctranspose and horzcat
Statistics functions such as max and min
Interoperability with Simulink

, Signal Processing Blockset software, Embedded MATLAB


subset, and Filter Design Toolbox software
Compatibility with the Simulink To Workspace and From Workspace blocks

John Bofarull Guix attached: -- 12 / 13


format hex; % 123456789A
n=10;
s=0;
for k=1:1:n
s=k+s;
disp(s);
end
3ff0000000000000
4008000000000000
4018000000000000
4024000000000000
402e000000000000
4035000000000000
403c000000000000
4042000000000000
4046800000000000
404b800000000000





John Bofarull Guix attached: -- 13 / 13
note 7:
t28fibonacci(30) %fibonacci slow maturity
ans =
1.0e+004 *
0.000100000000000 0
0.000100000000000 0
0.000200000000000 0
0.000300000000000 0.000150000000000
0.000400000000000 0.000133333333333
0.000600000000000 0.000150000000000
0.000900000000000 0.000150000000000
0.001300000000000 0.000144444444444
0.001900000000000 0.000146153846154
0.002800000000000 0.000147368421053
0.004100000000000 0.000146428571429
0.006000000000000 0.000146341463415
0.008800000000000 0.000146666666667
0.012900000000000 0.000146590909091
0.018900000000000 0.000146511627907
0.027700000000000 0.000146560846561
0.040600000000000 0.000146570397112
0.059500000000000 0.000146551724138
0.087200000000000 0.000146554621849
0.127800000000000 0.000146559633028
0.187300000000000 0.000146557120501
0.274500000000000 0.000146556326749
0.402300000000000 0.000146557377049
0.589600000000000 0.000146557295551
0.864100000000000 0.000146556987788
1.266400000000000 0.000146557111445
1.856000000000000 0.000146557169931
2.720100000000000 0.000146557112069
3.986500000000000 0.000146557111871
5.842500000000000 0.000146557130315
t28fibonacci(90)
%fibonacci slow maturity, not enough accuracy to show up
ans = 1.0e+014 *
0.000000000000010 0
0.000000000000010 0
0.000000000000020 0
0.000000000000030 0.000000000000015
0.000000000000040 0.000000000000013
0.000000000000060 0.000000000000015
0.000000000000090 0.000000000000015
0.000000000000130 0.000000000000014
0.000000000000190 0.000000000000015
0.000000000000280 0.000000000000015

0.079604636507910 0.000000000000015
0.116666265190000 0.000000000000015
0.170982721992970 0.000000000000015
0.250587358500880 0.000000000000015
0.367253623690880 0.000000000000015
0.538236345683850 0.000000000000015
0.788823704184730 0.000000000000015
1.156077327875610 0.000000000000015
1.694313673559460 0.000000000000015
2.483137377744190 0.000000000000015
3.639214705619800 0.000000000000015
5.333528379179260 0.000000000000015

loss of accuracy when using t28fibonacci(n) with high
enough n.

note 8:

Fibonacci slow maturity series execution delay

1. 0.000603092659156
2. 0.000533287891799
3. 0.000120618531831
4. 0.000111379665563
5. 0.000112406206260
6. 0.000170405755608
7. 0.000252529011323
8. 0.000454244258173
9. 0.000531234810406
10. 0.000820719286801
11. 0.003413247815650
12. 0.001786180811799
13. 0.002717766493814
14. 0.004163135794396
15. 0.008781542387662
16. 0.008292909016158
17. 0.011929942703631
18. 0.016585818032317
19. 0.023968698721084
20. 0.034856702617833
21. 0.050220423951042
22. 0.073305784402843
23. 0.106397350293154
24. 0.159265222700305
25. 0.232908225721928
26. 0.349603319011380
27. 0.513468983842763
28. 0.747834384083281
29. 1.096837690057594
30. 1.637226163853346
31. 2.347398309595435
32. 3.504358948432242
total delay 10.939030668416576
(12,0.0017861) (24,0.159265) (32,3.5043589)

Você também pode gostar