Please do this question in matlab and copy and paste the inp
(Please do this question in matlab and copy and paste the input and output)
Write a function array_product to compute the product of the elements of an array v using a for loop. The rst line of the function, and explanatory comments have been provided.
function P = array_product(v)
%array_product Product of elements in an array
% P = array_product(v) returns v(1) * v(2) * ... * v(n)
% where n is length(v).
Test your function for several arrays that you create, and conrm it recovers the same answer as the MATLAB built-in function prod.
Hint: What value should you initialise the variable P to in your function?
Solution
CODE
function P = array_product(v)
%array_product Product of elements in an array
% P = array_product(v) returns v(1) * v(2) * ... * v(n)
% where n is length(v).
P = 1;
for i=1:length(v)
P = P*v(i);
end
OUTPUT
For array: v=[1 2 3 4 5]
>> array_product(v)
ans =
120
>> prod(v)
ans =
120
