Reputation: 98
I'm attempting to take a general array A
, raise it to the (element-wise) power of each member of a vector p
, and sum the result, preferably in a vector operation, such that the result is the same size as A
. Ideally, arrays of any size/dimension for A
should be allowed. For example, if
A = [0 1 ; 2 3]
p = [2 3]
I want the result A.^p(1) + A.^p(2)
, which is [0 2 ; 12 36]
, just more elegantly, and for any size of A
and length of p
, and avoiding a loop.
I came up with the following, which expands into the next higher dimension of A
, then sums along that dimension:
sum(repmat(A,[ones(1,ndims(A)) length(p)]) .^ repmat(reshape(p,[ones(1,ndims(A)) length(p)]),size(A)),ndims(A)+1)
which technically seems to work, but....ugh. Is there a cleaner way to do this?
Upvotes: 0
Views: 204
Reputation: 15837
Assuming p
to be a row vector:
result = reshape(sum(A(:) .^ p, 2), size(A));
Upvotes: 3