How to calculate product of the odd positions and the sum of the even positions?
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
Roger Stafford
on 29 May 2015
Big hint (almost a give-away): vec_in(1:2:end) is the vector of all odd-positioned elements.
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!