Borrar filtros
Borrar filtros

How to calculate product of the odd positions and the sum of the even positions?

1 visualización (últimos 30 días)
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

Respuestas (1)

Roger Stafford
Roger Stafford el 29 de Mayo de 2015
Big hint (almost a give-away): vec_in(1:2:end) is the vector of all odd-positioned elements.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by