Answers are to be reported as pX= where X is the problem number. * For example the answer to problem i should be reported as pl- $ if it is a single part question, and pla= if it is a multipart $ question. This is how to report your answer for a single part question pl = sind (180); * This is how to report your answer for a multi-part question p2a = exp(-2*pi); p2b = fix (2*pi); p2c = mean (1:5); p2d = 'my answer is ...'; Problem 4: Use nested for loops to perform the following exercises. Do not use MATLB built-in function. (a) Create the 3-D function: M(x, y, z) = e-(sin(2x)cos(4y)tanh(z)]' in a rectangular domain with x = (-2:0.01:2]; y = (-1:0.01:1] and z = [0:0.01:1). Matrix M should have the dimension of length(x) by length(y) by length(z). Set p4a=M. (b) Compute the average value of M over the entire rectangular domain and put the answer into p4b. The answer should be a single number. (c) Compute the average values of M over the x-y planes and put the answer into p4c. The answer should be a vector with the dimension of length(z). (d) Compute the average values of M along the z-direction and put the answer into p4d. The answer should be a 2-D matrix with the dimension of length(x) by length(y). (e) Create figure 1. Use function surf to plot the answer in part (d), e.g. p4d, versus x and y. Remember to label the axes and give the figure a title. Set p4e='See figure 1'.

Respuesta :

Answer:

(a) Following is the matlab code:

a=1; %% index variable for x

b=1; %% index variable for y

c=1; %% index variable for z

for x=-2:0.01:2  %%  for loop goes through x

   for y=-1:0.01:1  %% nested for loop goes through y

       for z= 0:0.01:1  %% nested for loop goes through z

           M(a,b,c)=exp(-(sin(2*x)*cos(4*y)*tanh(z)));  %%Computing M

           c=c+1;

       end

       b=b+1;

       c=1;

   end

   a=a+1;

   b=1;

   c=1;

end

(b) v=mean(M(:)); %% (:) enables to calculate mean of all elements

(c)  f=mean(mean(M, 1), 2);   %% 1st along x, then along y

f=reshape(f,[size(f,3) 1]); %% reshaping into vector form

(d)  g=mean(M,3); %%along z

(e) surf(g)  %% surface plot

Explanation:

(a) We use three nested loops to compute M, 1st for loop goes over all values of x, second nested loop goes over y and third nested loop goes over z. We compute the expression in the third nested loop and then index it separately using variables a, b and c.

(b) To compute mean of all values we make use of (:) which enables to calculate mean of all elements in M.

(c) To compute along x-y plane, we first compute mean along x dimension and then along y dimension. Finally we reshape into vector form.

(d) We just mention the dimension 3 to compute mean along z dimension.

(e) We use surf function to plot g in part d.

ACCESS MORE