sum of function handle
古いコメントを表示
Dear all, i have the following function:
sum_{1<=i<j<=n}(X_i-X_j)
and i need to write it as function handle. Can anyone help me please. Best regards.
4 件のコメント
Write it as a function first, then the function handle part is trivial.
Trying to go straight from what you have there to a function handle is probably an unnecessarily complicated step unless for some reason you aren't allowed to create actual functions.
Guillaume
2015 年 12 月 15 日
Your function does not appear to be the same thing at all as the expression you wrote in your question. Why is there a third iterator k, why is there a square ^2 and later a square root sqrt ?
回答 (3 件)
Guillaume
2015 年 12 月 15 日
"I need to write it as function handle". Why do you need it? As Adam says, work it out as a normal function.
Anyway:
sumdiff = @(x) sum(diff(x(nchoosek(1:numel(x), 2)), [], 2)); %assume x is a vector
The way this works:
- nchoosek returns all the possible combinations of i and j that satisfy 1<=i<j<=n
- these combinations are use to index the original array as two columns, x(i) in the first column, x(j) in the second
- diff calculates the difference between the 2nd and 1st column
- sum sum all the differences
4 件のコメント
Heborvi
2015 年 12 月 15 日
Guillaume
2015 年 12 月 15 日
The matrix x may be unknown, that does not preclude writing the function as a regular function.
function s = sumdiff(x)
s = sum(reshape(triu(bsxfun(@minus, x(:), x(:).'), 1), [], 1)); %Matt's answer is more efficient than mine
end
You can include anything you like in a handle function if it isn't an anonymous function.
You literally just define your function and then use function handle syntax to create a handle to it. The function could be 5000 lines long if you really want (obviously not advisable!), e.g.
function s = sumdiff(x)
...
end
f = @(x) sumdiff(x)
s = f(x);
Matt J
2015 年 12 月 15 日
f=@(X) sum( reshape( triu( bsxfun(@minus, X(:),X(:).'),1), [],1) )
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!