BE 50 Spring/Summer 2016 Quiz 3 06/06/2016 1. There is a built-in MATLAB command
ID: 2315874 • Letter: B
Question
BE 50 Spring/Summer 2016 Quiz 3 06/06/2016 1. There is a built-in MATLAB command called prod It takes the product of all elements in a vector and returns the overall value. (Use the help command to familiarize yourself little a more with this built-in function.) Without using this function, write a script that prompts the user to input a vector; then using a for loop, determine the product of all elements in the vector. The only built-in commands you may use are input, size, and disp. Test your code on the following vector 1 -3 7 2 5 6 4] 2. Repeat #1 using a while loop.Explanation / Answer
for-loop code
prompt = 'Enter the vector : ';
x = input(prompt);
dim = size(x); %dimension
l = dim(1,2); %length of vector
p = 1; %initialising the output to 1
for i = 1:l
p = p*x(i); %iteratively multiplying the terms
end
prompt = 'Product is : ';
disp(prompt);
disp(p);
end code
PART B
while-loop code
prompt = 'Enter the vector : ';
x = input(prompt);
dim = size(x); %dimension
l = dim(1,2); %length of vector
p = 1; %initialising the output to 1
while l>0
p = p*x(l); %iteratively multiplying the terms
l = l-1;
end
prompt = 'Product is : ';
disp(prompt);
disp(p);
end code
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.