Solutions to C Moler MATLAB Experiments Chapter 2

Embed Size (px)

DESCRIPTION

Solutions to C Moler MATLAB Experiments Chapter 2

Citation preview

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    1/13

    John Bofarull Guix attached: -- 1/ 13

    MATLAB - CMOLER 2.- FIBONACCI

    source: Experiments with MATLAB - CMoler - bookCONTENTS

    Exercises: 2.1 to 2.8

    Fourier square pulse train exampleMATLAB as automation serverKronecker Tensor ProductLinear data regression example and literature examples

    Vectorizing code

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

    EXERCISES

    2.1 Walsh, f(n) even when n=3*k-1, k>=1why? 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 asstarting on two consecutive odds.

    2.2 Backslashc1 + c2 = 1;c1* phi + c2* phi = 1

    X = 0.7236067977499790.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 kronRelational operators.eq - Equal ==ne - Not equal ~=lt - Less than le - Less 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 ORany - True if any element of vector is nonzeroall - True if all elements of vector are nonzeroSpecial 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 slashMatrix division.\ Backslash or left division.

    A\B is the matrix division of A into B, which is roughly thesame 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 Ncomponents, or a matrix with several such columns, thenX = A\B is the solution to the equation A*X = B computed by

    Gaussian elimination. A warning message is printed if A isbadly scaled or nearly singular. A\EYE(SIZE(A)) produces theinverse of A.

    If A is an M-by-N matrix with M < or > N and B is a columnvector with M components, or a matrix with several such columns,then X = A\B is the solution in the least squares sense to theunder- or overdetermined system of equations A*X = B. Theeffective rank, K, of A is determined from the QR decompositionwith pivoting. A solution X is computed which has at most Knonzero components per column. If K < N this will usually notbe the same solution as PINV(A)*B. A\EYE(SIZE(A)) produces ageneralized inverse of A.

    / Slash or right division.

    B/A is the matrix division of A into B, which is roughly thesame 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 Bmust 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 Bmust 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.

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    2/13

    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 indexmetaclass - 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 samecommand order? )for k=1:1:15 tic; fibnum(k); disp(fibnum(k)); toc; end1 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

    fork=1:1:n tic; fibnum(k);disp(fibnum(k)); t(k)=toc; endp=1:n; plot(p,1+10*t,'o')

    notes 3, 4, 5.

    2.4 fibnum(n) execution time as function of fibnum(n-1) andfibnum(n-2) execution times: multiply times. exp(n)n=24;fork=1:1:n tic; fibnum(k); disp(fibnum(k));t(k)=toc; endp=1:nplot(p,1+10*t,'o')

    n=24; %scattered datafork=1:1:n tic; fibnum(k); disp(fibnum(k));t(k)=toc; endp=1:nplot(p,1+10*t,'o')% ordinary least square regression%bls=regress(1+10*t,[ones(10,1) p])%robust regressionbrob=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','RobustRegression')

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    3/13

    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=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 ,

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    4/13

    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.18rounding 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-precisionquantity 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+000format 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 andnumeric type Properties. format hexrealmax ans = 7fefffffffffffff; realmin ans = 0010000000000000format 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)functionf = t28fibonacci(n)f = zeros(n,1);f(1) = 1; f(2)=1;f(3) = 2;fork = 4:nf(k) = f(k-1) + f(k-3); end

    1 1 0 13 9 4 233 88 145 4181 8283353

    1 1 0 21 13 8 377 129 248 6765 1278 5487

    2 2 0 34 19 16 610 189 421 10946 1873 90733 3 0 55 28 27 987 277 710 17711 2745 149665 4 1 89 41 58 1597 406 1191 28657 4023 246348 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 thegroup/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.functionf = fib3(n)% FIBONACCI MODIFIED Fibonacci sequence with slower maturity

    format long;f=zeros(n,1);f(1)=1;f(2)=1;f(3)=2;fork = 4:1:nf(k) = f(k-1) + f(k-3);end

    ALSO

    % FIBNUM2(n) generates the nth Fibonacci slower maturity number.

    functionf = fibnum2(n)ifn

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    5/13

    John Bofarull Guix attached: -- 5/ 13

    2.6.d % tictoconfibnum2(n)n=14; fork=1:1:n tic; fibnum2(k);disp(fibnum2(k));

    m(k)=toc; endp=1:n; disp(m); s=0;forj=1:1:n s=m(j)+s; enddisp(s);

    for 32 terms for fibonacci slow maturity series total delay10.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 fibnum2.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.6536345867740470.724 + 0.5634i 0.724 - 0.5634i -0.887 + 0.3823i -0.887 - 0.3823i -0.163 + 0.8616i -0.163 - 0.8616i

    1. 12. 23. 34. 55. 86. 137. 218. 33

    9. 5210.8211.12912.203

    13.31914.50115.78716.123617.194118.304819.478620.7515

    21.1180022.1852823.2909224.45679

    2.7.a functionf = 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;fork = 8:1:nf(k) = f(k-1) + f(k-2)-f(k-7);end

    2.7.a functionf = fibnm3(n)% FIBNUM modified number.% FIBNM3(n) generates the nth Fibonacci number.ifn

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    6/13

    John Bofarull Guix attached: -- 6/ 13

    2.6.d % tictoconfibnm3(n)n=32; fork=1:1:n tic; fibnm3(k); disp(fibnm3(k));

    m(k)=toc; endp=1:n; disp(m); s=0;forj=1:1:n s=m(j)+s; enddisp(s);

    for 32 terms for fibonacci series total delay , againmanual 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.002252. 0.001063. 0.00016

    4. 0.000125. 0.000136. 0.000137. 0.000138. 0.000549. 0.0004710.0.0007811.0.0014712.0.0023013.0.00409

    14.0.00666815.0.01094116.0.017418

    17.0.02843518.0.04917119.0.08454120.0.15014421.0.21609222.0.34654823.0.57195524.0.977139

    25.1.785092626.2.691101027.4.4040258

    28.7.360734629.13.45651130.20.10373031.33.85505732.56.811253

    total:142.9402sec

    2.8 MATLAB Graphics Handles. Fibonacci's rabbit penfunction rabbits(action)

    % RABBITS Fibonacci's rabbit pen.% Create immature pushbuttons that age after one click.

    if nargin == 0clf resetshguicontrol('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 > 0set(gcbo,'enable','off')

    endend

    b = findobj(gcf,'style','pushbutton');if ~any(any(char(get(b,'enable')) == 'n'))

    set(b,'background','w','enable','on')endset(findobj(gcf,'style','text'),'string',length(b))

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    7/13

    John Bofarull Guix attached: -- 7/ 13

    2.9.1%function fibonacci no parametersn=25;f = zeros(n,1);f(1) = 1;f(2) = 2;fork = 3:nf(k) = f(k-1) + f(k-2);enddisp(f);

    2.10 functionfourier_demot = 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.

    fork = 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)

    endend

    % Even though the approximations are constantly% improving, they will never be exact because of the% Gibbs phenomenon, or ringing.

    functionupdatePlot(t,x)% Subfunction to update the plot

    claplot(t,x)

    end

    2.11% FIBNUM Fibonacci number.% FIBNUM(n) generates the nth Fibonacci number.

    functionf = fibnum(n)ifn MATLAB > Notebook, then MATLAB launches MSWordWelcome to the utility for setting up the MATLAB Notebookfor interfacing MATLAB to Microsoft Word

    Setup complete Warning: MATLAB is now an automation server

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    8/13

    John Bofarull Guix attached: -- 8/ 13

    2.14functionf=goldfract(n)%GOLDFRACT Golden ratio continued fraction.%GOLDFRACT(n) displays n terms.%assert(isa(n,'double'));

    p = '1';fork = 1:n

    p = ['1+1/('p ')'];endpp = 1;

    q = 1;fork = 1:ns = p;p = p + q;q = s;

    endp = sprintf('%d/%d',p,q)

    format longf = eval(p)

    format shorterr = (1+sqrt(5))/2 - pdisp(f);disp(err);

    2.15n=40fibonacci(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*^nfor some c and f(n)=f(n-1)+f(n-2) becomes^2= +1general solution to fibonacci recurrence:f(n)= c1*phi^n+c2*(1-phi)^ninitial 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 ProductThe Kronecker product, kron(X,Y), of two matrices is the larger matrix formed from all possible products of the elements of X withthose of Y. If X is m-by-nand 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 isthe 2-by-2 matrixX = 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) are1 0 2 00 1 0 23 0 4 00 3 0 4 and

    1 2 0 03 4 0 00 0 1 20 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.3208brob = 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 onplot(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')

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    9/13

    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 ComputingEnvironment." 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." Communicationsin 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 codefor i=1:n; y)i_=sin(2*pi*i/m); vectorized: i=1:n; y=sin(2*pi*i/m);

    2.19EXCEL 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 functionsmldivideandmrdivide.mldivideandmrdivideare used for the two situations where the unknown matrix appears on the left or right of thecoefficient matrix:

    X = B/A Denotes the solution to the matrix equation XA= B.

    X = A\B Denotes the solution to the matrix equationAX= B.

    Think of "dividing" both sides of the equationAX= Bor XA= BbyA. 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 formAX = Boccur more frequently than those of the form XA = B. Consequently, thebackslash is used far more frequently than the slash. The remainder of this section concentrates on the backslashoperator; 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 mnonzero components.

    The mldivide AlgorithmThemldivideoperator employs different algorithms to handle different kinds of coefficient matrices. The various casesare diagnosed automatically by examining the coefficient matrix.Permutations of Triangular Matricesmldividechecks for triangularity by testing for zero elements. If a matrix A is triangular, MATLAB software uses asubstitution to compute the solution vector x. If A is a permutation of a triangular matrix, MATLAB software uses apermuted substitution algorithm.Square MatricesIf A is symmetric and has real, positive diagonal elements, MATLAB attempts a Cholesky factorization. If the Choleskyfactorization fails, MATLAB performs a symmetric, indefinite factorization. If A is upper Hessenberg, MATLAB usesGaussian 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 factorizationwith partial pivoting (seelu).Rectangular MatricesIf A is rectangular,mldividereturns a least-squares solution. MATLAB solves overdetermined systems with QRfactorization (seeqr). For an underdetermined system, MATLAB returns the solution with the maximum number of zeroelements.

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    10/13

    John Bofarull Guix attached: -- 10/ 13

    Themldividefunction reference page contains a more detailed description of the algorithm.

    linear equations systems: AX= 0. Solve this using thenullcommand, by typing null(A).

    AX = b , exampleA = pascal(3);u = [3; 1; 4];x = A\ux = 10

    -125

    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 samecommand order? exampletic; fibnum(10); toc;Elapsed time is 0.007717 seconds.for k=1:1:15 tic; fibnum(10); toc; endElapsed 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.0019642856226302. 2.237858718230490e-0043. 2.694669328144512e-0044. 2.766527176895033e-0045. 4.244745779762879e-0046. 7.103661619337153e-0047. 0.0011995128037858. 0.0021901245758469. 0.003450716551070

    10.0.00538420595280711.0.01002057700826012.0.02609055834061713.0.04276055271004214.0.03941505658035715.0.07092934269059416.0.10392236067404717.0.15777314579803518.0.25479971934377419.0.41420814447123120.0.70892951822905321.1.22794438818431122.1.84333500488376723.3.09846167743935624. 4.779863993623129

    fibonacci n=32:1. 12. 23. 34. 55. 86. 137. 218. 349. 55

    10.8911.14412.23313.37714.61015.98716.159717.258418.418119.676520.1094621.17711

    22.2865723.4636824.7502525.12139326.19641827.317811

    fibnum execution delays up to n=321. 0.0006949680514872. 0.0004106162785743. 0.0001165123690454. 0.0001652730521265. 0.0002622811479396. 0.0004516779064327. 0.0007052334584528. 0.0011907872078669. 0.001960692730193

    10.0.00332085915297011.0.00734284560160712.0.00886828507651113.0.01174721845966514.0.01792955980395115.0.02844082326510816.0.04534384237262317.0.07372461300698918.0.11822669200853519.0.19013586779387720.0.31584655474977821.0.493183513140491

    22.0.79287129078767023.1.25335332350249524.2.00517530492108225.3.21239024355191326.5.19878293335030527.8.533724684864838

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    11/13

    John Bofarull Guix attached: -- 11/ 13

    28.51422929.83204030.134626931.217830932.3524578

    28.13.89696457048767429.22.72191525803896930.36.93998124510147831.59.54822251912060732.95.565903656076017

    total delay: 2.509893537464373e+002 = 4'10''

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

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

    x0=[24;48;-10]x = 1.0e+007 * -0.012746484169181 0.006355841042157 3.661172592962217fval = 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 MATLABtechnical computing software

    and enables algorithm development by providing fixed-point arithmetic. The toolbox enables you to create the

    following types of objects:

    fiDefines a fixed-point numeric object in the MATLAB workspace. Each fiobject is composed of

    value data, a fimathobject, and a numerictypeobject.

    fimathGoverns how overloaded arithmetic operators work with fiobjects

    fiprefDefines the display, logging, and data type override preferences of fiobjects

    numerictypeDefines the data type and scaling attributes of fiobjects

    quantizerQuantizes 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 thedividefunction 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 asctransposeandhorzcat

    Statistics functions such asmaxandmin

    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

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    12/13

    John Bofarull Guix attached: -- 12/ 13

    format hex; % 123456789An=10;s=0;fork=1:1:n

    s=k+s;disp(s);

    end3ff0000000000000400800000000000040180000000000004024000000000000402e000000000000

    4035000000000000403c00000000000040420000000000004046800000000000404b800000000000

  • 5/20/2018 Solutions to C Moler MATLAB Experiments Chapter 2

    13/13

    John Bofarull Guix attached: -- 13/ 13

    note 7:t28fibonacci(30) %fibonacci slow maturityans =1.0e+004 *0.000100000000000 00.000100000000000 00.000200000000000 00.000300000000000 0.0001500000000000.000400000000000 0.0001333333333330.000600000000000 0.000150000000000

    0.000900000000000 0.0001500000000000.001300000000000 0.0001444444444440.001900000000000 0.0001461538461540.002800000000000 0.0001473684210530.004100000000000 0.0001464285714290.006000000000000 0.0001463414634150.008800000000000 0.0001466666666670.012900000000000 0.0001465909090910.018900000000000 0.0001465116279070.027700000000000 0.0001465608465610.040600000000000 0.0001465703971120.059500000000000 0.000146551724138

    0.087200000000000 0.0001465546218490.127800000000000 0.0001465596330280.187300000000000 0.0001465571205010.274500000000000 0.0001465563267490.402300000000000 0.0001465573770490.589600000000000 0.0001465572955510.864100000000000 0.0001465569877881.266400000000000 0.0001465571114451.856000000000000 0.0001465571699312.720100000000000 0.0001465571120693.986500000000000 0.0001465571118715.842500000000000 0.000146557130315

    t28fibonacci(90)%fibonacci slow maturity, not enough accuracy to show up

    ans = 1.0e+014 *0.000000000000010 00.000000000000010 00.000000000000020 00.000000000000030 0.0000000000000150.000000000000040 0.0000000000000130.000000000000060 0.000000000000015

    0.000000000000090 0.0000000000000150.000000000000130 0.0000000000000140.000000000000190 0.0000000000000150.000000000000280 0.0000000000000150.079604636507910 0.0000000000000150.116666265190000 0.0000000000000150.170982721992970 0.0000000000000150.250587358500880 0.0000000000000150.367253623690880 0.0000000000000150.538236345683850 0.0000000000000150.788823704184730 0.000000000000015

    1.156077327875610 0.0000000000000151.694313673559460 0.0000000000000152.483137377744190 0.0000000000000153.639214705619800 0.0000000000000155.333528379179260 0.000000000000015

    loss of accuracy when using t28fibonacci(n) with highenough n.

    note 8:

    Fibonacci slow maturity series execution delay

    1. 0.0006030926591562. 0.0005332878917993. 0.0001206185318314. 0.0001113796655635. 0.0001124062062606. 0.0001704057556087. 0.0002525290113238. 0.0004542442581739. 0.00053123481040610.0.00082071928680111.0.00341324781565012.0.00178618081179913.0.00271776649381414.0.00416313579439615.0.00878154238766216.0.008292909016158

    17.0.01192994270363118.0.01658581803231719.0.02396869872108420.0.03485670261783321.0.05022042395104222.0.07330578440284323.0.10639735029315424.0.15926522270030525.0.23290822572192826.0.34960331901138027.0.51346898384276328.0.74783438408328129.1.09683769005759430.1.63722616385334631.2.34739830959543532.3.504358948432242

    total delay 10.939030668416576(12,0.0017861) (24,0.159265) (32,3.5043589)