lab1 solutions

Upload: greatfaber

Post on 05-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Lab1 Solutions

    1/9

    1

    CMLab #1 Solutions

    LAB #1 Solutions

    2) Using the special matrices ones, zeros and eye, assign the matrix:A=[0 0 1 2 3 1 0 0

    0 0 2 1 2 0 1 01 1 3 2 1 0 0 1

    1 1 0 0 0 3 3 31 1 0 0 0 3 3 3

    2 4 0 0 0 6 6 6

    2 4 2 0 0 7 0 0

    2 4 0 2 0 0 7 0]

    % EXERCISE 2

    clear allclose allclc

    % Some different matrices will be created in order to compose the A matrix.a1=[zeros(2,2); ones(1,2)];a2=(ones(3))+diag(diag(ones(2)),-1)+diag(diag(2*ones(1)),-2) ...

    +diag(diag(ones(2)),1)+diag(diag(2*ones(1)),2); a3=eye(3);b1=ones(2,2);b2=zeros(2,3);b3=3*ones(2,3);

    c1=2*ones(3,1);c2=4*ones(3,1);c3=zeros(3)+diag(diag(2*ones(2)),-1); c4=[6; 7; 0];c5=[6; 0; 7];c6=[6; 0; 0];

    % Finally, putting together the matrices we obtain the A matrixA=[a1 a2 a3; b1 b2 b3; c1 c2 c3 c4 c5 c6]

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 7/31/2019 Lab1 Solutions

    2/9

    2

    CMLab #1 Solutions

    3) Assign the matrix Q:Q=[1 2 3 4 5 6 7 8 9

    2 3 4 5 6 7 8 9 1

    3 4 5 6 7 8 9 1 2

    4 6 8 1 3 5 7 9 2

    1 3 5 7 9 2 4 6 89 7 5 3 1 8 6 4 2

    6 8 2 9 7 5 3 1 4

    8 1 3 5 7 9 2 4 6

    4 6 4 6 4 8 6 8 6]

    And then:

    a) Compute the sum of the terms in the odd columns.

    b) Compute the sum of the terms in the main diagonal.

    c) Compute the sum of the outermost frame elements, which are not 4.

    d) Compute the sum of all the matrix terms, excluding those equal to 9, close to 7.

    % EXERCISE 3

    clear allclose allclc

    % Matrix Q assignmentaa=[4 6];bb=[8 6];Q=[1:9;2:9 1; 3:9 1 2; 4:2:8 1:2:9 2; ...1:2:9 2:2:8;9:-2:1 8:-2:2; 6 8 2 9:-2:1 4;...

    8 1:2:9 2:2:6; aa aa 4 bb bb];% s is a the two-element row vector containing the number of rows, s(1),and% columns, s(2), in the matrix Qs=size(Q);

    %% Point a% Vector 'c_odd' contains the odd numbers from one to the number of% columns of the matrix Qc_odd=1:2:s(2);% Selection of the odd columns of Q, the first summation is referred% to the columns, obtaining a row vector, then its element are summed upresult_a=sum(sum(Q(:,c_odd)));disp(['Result of point a: ',num2str(result_a)])

    %% Point b% 'diag(Q)' contains the element on the main diagonal of Q, then these% elements are summed upresult_b=sum(diag(Q));disp(['Result of point b: ',num2str(result_b)])

    %% Point c% Selection of the element of the frame, look at the transposition for the% column vectors!frame=[Q(1,:),Q(2:end-1,1)',Q(end,:),Q(2:end-1,end)']; % Selection of the indices of the elements different from 4frame_no4=find(frame~=4);

    % Selection of the elements with the indices contained in 'frame_no4' and% sum of themresult_c=sum(frame(frame_no4));disp(['Result of point c: ',num2str(result_c)])

  • 7/31/2019 Lab1 Solutions

    3/9

    3

    CMLab #1 Solutions

    %% Point d% Q1 is simply a copy of the original matrix QQ1=Q;% Index is a row vectors containing the indices of the elements equal to 9index=find(Q==9);

    % We could start looking for the elements above the 9swww=Q(index-1)';% Check if these elements are equal to 7z=find(www==7);a=index(z);% We exclude the 7s those stay on the last row, because they aren't above a% 9 in the matrix Q, even if this is true referring to the vector 'index'% with the function 'mod' is easy to check if some elements of a are multiple% of the number of rows s(1); in this case with 'mod(a,s(1))~=1' we find% those that are on the last rowb=a(find(mod(a,s(1))~=1));Q1(b)=0;% Now we are looking for the elements under the 9s

    www=Q(index+1)';z=find(www==7);a=index(z);% For the same reason we exclude the 7s those stay on the first rowb=a(find(mod(a,s(1))~=0));Q1(b)=0;% Now we are looking for the elements on the right of the 9sindex_r=index+s(1);% Here we translate the indices by the length of a row (s(1)) but then we% have to check that the indices don't overcame the maximum index of Q,% that is equal to s(1)*s(2); this happens for a 9 in the last columnindex_r=index_r(index_r0);www=Q(index_l)';z=find(www==7);a=index_l(z)+s(1);Q1(a)=0;

    % Finally we can compute the resultresult_d=sum(sum(Q1));disp(['Result of point d: ',num2str(result_d)])

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 7/31/2019 Lab1 Solutions

    4/9

    4

    CMLab #1 Solutions

    4) Execute the following MATLAB commands:clear all; tic; for k=1:6e4; a(k) = k; end; toc;

    clear all; tic; a = zeros(1, 6e4); tic; for k=1:6e4; a(k) = k; end; toc;

    clear all; tic; a = [1:6e4]; toc;

    Try to explain the difference in the execution times.

    % EXERCISE 4

    clear allclose allclc

    % Section a)clear all;tic;for k=1:6e4;

    a(k) = k;end;toc;

    % Section b)clear all;tic;a = zeros(1, 6e4);for k=1:6e4;

    a(k) = k;end;toc;

    % Section c)

    clear all;tic;a = [1:6e4];toc;

    % Conclusions:% a) -> vector is created during the "for" loop execution: it takes lot of time% b) -> vector initialized like all zeros so we just have to change old% values whit new instead to create new element positions during the cycle% execution% c) -> we don't have a cycle, we are just creating a vector which directly% contains the right elements

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 7/31/2019 Lab1 Solutions

    5/9

    5

    CMLab #1 Solutions

    5) We want to plot the function y=sin(x) with 0x50, using the MATLAB pre-defined functionsin(x).

    a) Assign a vector x containing all the points from 0 e 50, with increment 0.01, and compute

    the y vector, either with a for loop and with an array-smart command.

    b) Plot y as a function of x.

    c) Use the commands xlabel, ylabel, gtext, title to complete the plot; then save your work in apostscript file using the instruction:print -depsc filename.

    %EXERCISE 5

    clear allclose allclc

    % Section a)xxx=(0:0.01:50); % x-vector declaration% 'for' cycle to build the y-vector

    for iii=1:length(xxx)yyy1(iii)=sin(xxx(iii));endyyy2=sin(xxx); % building directly the y-vector

    % Section b)% Initialization of word dimension in the graphwords=20;set(gca,'fontsize',words);% Initialization of line width in the graphline=1.5;set(0,'defaultlinelinewidth',line);% Opening the figure

    figure (1)plot(xxx,yyy2,'r'); % plotting the sin function

    % Section c)grid on% adding a gridxlabel('x'); % giving a name to each axesylabel('y');% Fixing the maximum values to be plotted for each axisaxis([0 50 -2 2]);title('Exercise 5'); % giving a title to the figure% Putting an explanation text in a point of the figure specified through% a click of the mousegtext('y=sin(x)','fontsize',words);

    printdepsc

    f1 Ex5c

  • 7/31/2019 Lab1 Solutions

    6/9

    6

    CMLab #1 Solutions

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 7/31/2019 Lab1 Solutions

    7/9

    7

    CMLab #1 Solutions

    6) Try to assign, evaluate and plot the function 1/(1+x^2) in the range [-2:2] using the followinginstructions:

    A. fun='1./(1+x.^2)'; y=eval('fun'); fplot(fun,[-2,2])or

    fplot('1./(1+x.^2)',[-2,2])

    B. x=linspace(-2,2); fun=inline('1./(1+x.^2)'); y=fun(x); plot(x,y)or

    x= linspace(-2,2); fun=inline('1./(1+x.^2)'); y=feval(fun,x); plot(x,y)

    C. x= linspace(-2,2); fun=@(x)[1./(1+x.^2)] (anonymous function); y=fun(x); plot(x,y)D. by building a suitable function in a .m file.

    % EXRCISE 6

    clear allclose allclc

    % Definition of the extreme values of the domainxmin=-2;xmax=2;

    % Section a)fun='1./(1+x.^2)';% In this case we don't need to define an "x" discretization because% the variable "y" is simply a string and not a vector with values inside,

    % so we just define the extreme values between which limiting the function% ploty=eval('fun');% We are plotting a function evaluated between two points and so we use% the command "fplot"figure(1)fplot(fun,[xmin,xmax],'b')% Or a different expression to plot the same resultsHold onfplot('1./(1+x.^2)',[-2,2],'r--')% We can see that the two graphs drawn in blue and in red are exactly superposed

    % Section b)fun=inline('1./(1+x.^2)');% Indeed in this case we are considering with a "y" variable that is% composed by several values, so we need to define in advance an% independent variable called "x" that has to be a vector containing the% discretized domain of the function that we want to plot. To do this we% can easily use the command "linspace"x=linspace(xmin,xmax);y=fun(x);% Or a different expression to get the same resulty=feval(fun,x);% Now we have to plot two vectors using the command "plot"figure(3)plot(x,y,'g')

    % Section c)% The following command is used to define an anonymous function that will

  • 7/31/2019 Lab1 Solutions

    8/9

    8

    CMLab #1 Solutions

    % be used, in this case, to plot the values. The procedure is the as for section% a).fun=@(x)[1./(1+x.^2)] ;figure(4)fplot(fun,[-2,2],'k')

    % Section d)% In a new script we need to type a function (.m file) to be called afterwards% during the execution of the script. In a new .m file (called my_func.m) we% have to type:functiony = my_func(x)y=1./(1+x.^2);

    % Then we go back to the main script and we define a vector% containing 100 points linearly equally spaced between -2 and 2xx=linspace(-2,2);% 'my_func(xx)' evaluates our function on these points, then we plot themplot(xx,my_func(xx),'b');

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 7/31/2019 Lab1 Solutions

    9/9

    9

    CMLab #1 Solutions

    7) Compute the solution of the equation 1 - x^2 = exp(x) using one of the instructions listed above,and the instruction fzero. Try to apply fzero in the following ways: fzero(fun,attemptvalue),

    fzero('function', attemptvalue), fzero(@anonymous function, attemptvalue).

    % EXERCISE 7

    clear allclose allclc

    % First of all it is trivial to understand that this function has one solution% in the origin (0,0), so we have to look for the other solution, for% example with a graphical approach:% function declarationfun='1-x.^2-exp(x)';% Plotfplot(fun,[-2 2]);grid on

    % We could see that the other root is between -1 and -0.5, so a good choice% for the attempt value could be -0.75root=fzero(fun,-0.75)% On the other hand, if we try with an attempt value too close to zero, we% find 0!root=fzero(fun,-0.1)

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%