Vectorized exponentiation

2020-04-21 01:43发布

I have two vectors, X of bases and N of exponents. I want to get the matrix of all values e = xn for each x in X and n in N.

For example, the following input:

X = [2 3 4]'
N = [1 2 3]

should produce:

ans = [2 4 8; 3 9 27; 4 16 64]

Is there a way to get this without looping (just like you can get all values of x×n by using the column by row product)?

2条回答
Root(大扎)
2楼-- · 2020-04-21 01:56

This is probably a bit sloppier than the bsxfun answer, but you could use meshgrid:

E = X.^(meshgrid(N)')

This assumes both X and N are row vectors. If both are column vectors then it becomes:

E = X.^(meshgrid(N))
查看更多
够拽才男人
3楼-- · 2020-04-21 02:13

Use bsxfun:

bsxfun(@power, X, N)

This assumes that X is a column vector and N is a row vector. If you want to guarantee that, use the following syntax which is more robust:

bsxfun(@power, X(:), N(:).')
查看更多
登录 后发表回答