How to sum elements in a vector according to the location information from another vector?

2 ビュー (過去 30 日間)
Hello,
I have a vector lets say V=[3 5 3 7 1 7 9 3 9 2 0 3 9]
and another vector that is indicating the which elements that are needed to be summed. Lets say L=[1 4 5 6 8]
So my output should be the sum of first,fourth,fifth,sixth and eighth elements in V. I.e. sum=3+7+1+7+3=21
How can this code be to get the sum value?
Thanks in advance!

採用された回答

Ahmet Cecen
Ahmet Cecen 2016 年 3 月 19 日

その他の回答 (1 件)

Muhammad Usman Saleem
Muhammad Usman Saleem 2016 年 3 月 19 日
編集済み: Muhammad Usman Saleem 2016 年 3 月 19 日
I have convert this question to a function. Please check it and tell me if not working
function sum1=runsum(V,L)
runsum=0;
for i=1:length(L)
runsum=runsum+V(L);
end
sum1= runsum;
end
  3 件のコメント
Muhammad Usman Saleem
Muhammad Usman Saleem 2016 年 3 月 19 日
my code seem working more efficiently than other. It depend on your own requirement...
Stephen23
Stephen23 2016 年 3 月 19 日
編集済み: Stephen23 2016 年 3 月 19 日
@Muhammad Usman Saleem: not only is your code ten times slower than Ahmet Cecen's, your code also does not give the correct answer:
>> [A,B] = test(1e5)
Elapsed time is 0.183132 seconds. % Ahmet's code (fast)
Elapsed time is 1.775014 seconds. % Your code (slow)
A =
21 % Ahmet's code (correct)
B =
15 35 5 35 15 % Your code (incorrect)
Your code has one obvious bug (keyword: indexing), and the fact that its output is obviously incorrect shows that you never tested your code. It is also pointless to reinvent perfectly good inbuilt functionality.
The test file is here, so you can try it yourself (I used R2012b):

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMultirate Signal Processing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by