The j-th cumulative product of a vector x = (x1, x2, . . . , xn), for j n is def
ID: 3760846 • Letter: T
Question
The j-th cumulative product of a vector x = (x1, x2, . . . , xn), for j n is defined by pj = x1 · x2 · · · xj . The cumulative product vector P contains all of the cumulative products as its elements, i.e. P = [p1 p2 . . . pn] where n is the number of elements in the vector x .
For example, the cumulative product vector P of the vector x=[3 5 8 1 2 7] is P = [ 3 15 120 120 240 1680] Write a MATLAB function calc_prod(x) that computes and returns the cumulative product vector of the vector x. You must make sure that the vector x contains only numbers and if not return an appropriate error message.
Hint : The MATLAB function isnumeric(A) returns 1 if A is a numeric array and 0 otherwise.
Explanation / Answer
function P=calc_prod(x)
if(isnumeric(x)~=1)
error('x must be Numeric array');
end
% Assign first value to output P
P(1)=x(1);
% start loop from 2 to number of elements in x
for ii=2:numel(x)
P(ii)=P(ii-1)*x(ii); % Calculate last product result*current element
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.