How to calculate product of the odd positions and the sum of the even positions?
1 次查看(过去 30 天)
显示 更早的评论
Question: The script should assume vec_in is specified at the command line. The script should multiply the values at the odd locations of vec_in and subtract the sum of values at the even location of vec_in. For example, given
>> vec_in = [1 2 3 4 5]; script23_drew_murray;
vec_value =
9 % This is the result of the calculation 1*3*5 – (2+4).
I have written this code using logic. I am not sure why it is calling out the entire array when I assign the even(ctr). How do I get it to use one value of ii at a time?
ctr = 0 ;
product = 1;
sum = 0;
for ii = vec_in(1):vec_in(end);
ctr = ctr + 1;
if ctr == 1:2:length(vec_in);
odd(ctr) = ii;
product = product*odd(ctr);
else ctr == 2:2:length(vec_in);
even(ctr) = ii;
sum = sum + even(ctr);
end
end
vec_value = product - sum
0 个评论
回答(1 个)
Roger Stafford
2015-5-29
Big hint (almost a give-away): vec_in(1:2:end) is the vector of all odd-positioned elements.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!