Compute the cumulative product of the elements in a vector. The cumulative produ
ID: 3808525 • Letter: C
Question
Compute the cumulative product of the elements in a vector. The cumulative product of the j th element of the vector x, x_j, is defined by: P_j = x_1x_2x_3 ... x_j for j = 1: length of the vector x. create 2 different versions of this function: I. One that uses two for-loops to explicitly carry out the calculations, element by element. An "inner" loop should accumulate the product and an "outer" loop should move through the elements of the vector p. II. One that uses the built-in function prod to replace the inner loop. In each case, you can check your results with the built-in function, compared.Explanation / Answer
Matlab code
x = [1 1 1 1 1 2 3 4 5 6]; % Create a vector x
N = length(x);
% Part I.
for j =1:N % Selecting jth element
P(j) = 1;
for k = 1:j % Taking numbers from 1 to j
P(j) = P(j)*x(k); % Finding product
end
end
disp('First version result');
disp(P);
% part II
for j = 1:N
P(j) = prod(x(1:j)); % Finding product
end
disp('Second version result');
disp(P);
% Using cumprod
P = cumprod(x);
disp('First version result');
disp(P);
OUTPUT
First version result
1 1 1 1 1 2 6 24 120 720
Second version result
1 1 1 1 1 2 6 24 120 720
First version result
1 1 1 1 1 2 6 24 120 720
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.