anonymous function which outputs a vector of sums when the input is a vector of indices.

I'd like to write an anonymous function such as
f = @(X,m,A) sum(X(m:A))
where X is a vector,
m < numel(X),
and A is a subset of
[ m+1,numel(X) ],
which outputs a vector, the i'th element of which is sum(X(m:A(i)))
For example, let
X = [ 1:7 ], m = 4, A = [5:6]
I'd like my function f(X,m,A) to output
[ 4+5, 4+5+6 ]= [ 9 , 15 ]
Thanks for any help!!

1 件のコメント

Walter Roberson
Walter Roberson 2015 年 11 月 7 日
If your A are always going to be consecutive then you can use cumsum()

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

 採用された回答

per isakson
per isakson 2015 年 11 月 7 日
編集済み: per isakson 2015 年 11 月 7 日
Try
>> f = @(X,ix1,ix2) arrayfun( @(ix) sum(X(ix1:ix)), ix2 );
>> f([1:7],4,[5:6])
ans =
9 15
>> f([1:7],4,[5,7])
ans =
9 22
>> f([1:7],4,[7,5])
ans =
22 9
it seems to do it!

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索

質問済み:

2015 年 11 月 7 日

コメント済み:

2015 年 11 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by