Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing the creation of a matrix of successive powers

Let x=1:100 and N=1:10. I would like to create a matrix x^N so that the ith column contains the entries [1 i i^2 ... i^N].

I can easily do this using for loops. But is there a way to do this using vectorized code?

like image 780
alext87 Avatar asked Oct 13 '10 07:10

alext87


3 Answers

I'd go for:

x = 1:100;
N = 1:10;
Solution = repmat(x,[length(N)+1 1]).^repmat(([0 N])',[1 length(x)]);

Another solution (probably much more efficient):

Solution = [ones(size(x)); cumprod(repmat(x,[length(N) 1]),1)];

Or even:

 Solution = bsxfun(@power,x,[0 N]');

Hope this helps.

like image 105
Adrien Avatar answered Nov 16 '22 03:11

Adrien


Sounds like a Vandermonde matrix. So use vander:

A = vander(1:100);
A = A(1:10, :);
like image 29
Oliver Charlesworth Avatar answered Nov 16 '22 01:11

Oliver Charlesworth


Since your matrices aren't that big, the most straight-forward way to do this would be to use MESHGRID and the element-wise power operator .^:

[x,N] = meshgrid(1:100,0:10);
x = x.^N;

This creates an 11-by-100 matrix where each column i contains [i^0; i^1; i^2; ... i^10].

like image 45
gnovice Avatar answered Nov 16 '22 02:11

gnovice