フィルターのクリア

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

1 回表示 (過去 30 日間)
LEP
LEP 2015 年 5 月 29 日
回答済み: Roger Stafford 2015 年 5 月 29 日
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

回答 (1 件)

Roger Stafford
Roger Stafford 2015 年 5 月 29 日
Big hint (almost a give-away): vec_in(1:2:end) is the vector of all odd-positioned elements.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by