How can I calculate the product of elements in even positions in a vector using a for loop, without using sum or prod built-in functions?

I'm having trouble calculating the product of even positions in a given matrix using a for loop. The vector is 100,000 uniformly randomly generated numbers between 0 and 50, and I know that is uniform=(50)*rand(1,100000). I don't know how to get the product of the even positions using for loops, without using prod function. Any help would be appreciated

답변 (1개)

Hi,
you can use the modulo function to detect the even positions and then simply multiply the values.
z = (50)*rand(1,100000);
r = 0
for ii = 1:n
if ~mod(ii,2)
r = r*z(ii)
end
end

댓글 수: 4

@Lessmann: An initial r value of zero means that the output is also going to be zero, no matter how many times you multiply it by some finite random number.
Hers is that code corrected and simplified:
V = 50 * rand(1,100000);
X = 1;
for k = 2:2:numel(V)
X = X*V(k);
end
But the concept is still flawed for the task given: the task is to calculate the product of 100000 random numbers between 0 and 50. Consider the maximum size of a double is
>> realmax
ans = 1.7977e+308
or ~10^308 whereas the average expected answer of this task will be approximately
>> 25^100000
ans = Inf
How can a numeric data class with a maximum value of ~10^308 be used to calculate a value ~25^100000 ?
Sorry, you are correct. The product of the even positions of the vector are then divided by the sum of the odd positions. If help could be provided here as well that would be great.
Expected value of the result is 25^100000/(100000*25).
Still much too large in magnitude.
Best wishes
Torsten.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 11월 4일

댓글:

2015년 11월 5일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by