Sei sulla pagina 1di 9

1

LAB #1 Solutions
2) Using the special matrices ones, zeros and eye, assign the matrix: A=[0 0 1 1 1 2 2 2
% EXERCISE 2 clear all close all clc % 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 matrix A=[a1 a2 a3; b1 b2 b3; c1 c2 c3 c4 c5 c6]

0 0 1 1 1 4 4 4

1 2 3 0 0 0 2 0

2 1 2 0 0 0 0 2

3 2 1 0 0 0 0 0

1 0 0 3 3 6 7 0

0 1 0 3 3 6 0 7

0 0 1 3 3 6 0 0]

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

CM Lab #1

Solutions

3) Assign the matrix Q: Q=[1 2 3 4 1 9 6 8 4 2 3 4 6 3 7 8 1 6 3 4 5 8 5 5 2 3 4 4 5 6 1 7 3 9 5 6 5 6 7 3 9 1 7 7 4 6 7 8 5 2 8 5 9 8 7 8 9 7 4 6 3 2 6 8 9 1 9 6 4 1 4 8 9 1 2 2 8 2 4 6 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 all close all clc % Matrix Q assignment aa=[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 Q s=size(Q); %% Point a % Vector 'c_odd' contains the odd numbers from one to the number of % columns of the matrix Q c_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 up result_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 up result_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 4 frame_no4=find(frame~=4); % Selection of the elements with the indices contained in 'frame_no4' and % sum of them result_c=sum(frame(frame_no4)); disp(['Result of point c: ',num2str(result_c)]) CM Lab #1 Solutions

%% Point d % Q1 is simply a copy of the original matrix Q Q1=Q; % Index is a row vectors containing the indices of the elements equal to 9 index=find(Q==9); % We could start looking for the elements above the 9s www=Q(index-1)'; % Check if these elements are equal to 7 z=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 row b=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 row b=a(find(mod(a,s(1))~=0)); Q1(b)=0; % Now we are looking for the elements on the right of the 9s index_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 column index_r=index_r(index_r<s(1)*s(2)); www=Q(index_r)'; z=find(www==7); % Now we move back to the original notation for the indices a=index_r(z)-s(1); Q1(a)=0; % Now we are looking for the elements on the left of the 9s index_l=index-s(1); % Again we translate the indices by the length of a row s(1), but then we % have to check that the indices don't became negative; this happens for a 9 % in the first column index_l=index_l(index_l>0); www=Q(index_l)'; z=find(www==7); a=index_l(z)+s(1); Q1(a)=0; % Finally we can compute the result result_d=sum(sum(Q1)); disp(['Result of point d: ',num2str(result_d)])

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

CM Lab #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 all close all clc % 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

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

CM Lab #1

Solutions

5) We want to plot the function y=sin(x) with 0x50, using the MATLAB pre-defined function sin(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 a postscript file using the instruction: print -depsc filename.
%EXERCISE 5 clear all close all clc % 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)); end yyy2=sin(xxx); % building directly the y-vector % Section b) % Initialization of word dimension in the graph words=20; set(gca,'fontsize',words); % Initialization of line width in the graph line=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 grid xlabel('x'); % giving a name to each axes ylabel('y'); % Fixing the maximum values to be plotted for each axis axis([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 mouse gtext('y=sin(x)','fontsize',words); print depsc f1 Ex5c

CM Lab #1

Solutions

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

CM Lab #1

Solutions

6) Try to assign, evaluate and plot the function 1/(1+x^2) in the range [-2:2] using the following instructions: 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 all close all clc % Definition of the extreme values of the domain xmin=-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 % plot y=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 results Hold on fplot('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 result y=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 CM Lab #1 Solutions

8 % 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: function y = 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 2 xx=linspace(-2,2); % 'my_func(xx)' evaluates our function on these points, then we plot them plot(xx,my_func(xx),'b');

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

CM Lab #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 all close all clc % 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 declaration fun='1-x.^2-exp(x)'; % Plot fplot(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.75 root=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)

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

CM Lab #1

Solutions

Potrebbero piacerti anche