user2051561
user2051561

Reputation: 837

octave vectorize function application

For a given (m by n) matrix poly I would like generate its lines with the following expression:

poly(i, :) = [X(i) X(i)^2 X(i)^3 ... X(i)^p]

I am given a (m by 1) X vector and the value p. My current solution is:

poly(:,1) = X;
for i = 2:p
    poly(:,i) = X.^i;
end;

My question is: is their any way to further vectorize this? I also generated a cell array of functions that could be applied to the matrix row by row, but I still had to loop.

TIA

Upvotes: 1

Views: 531

Answers (1)

uvesten
uvesten

Reputation: 3355

Sure, it's possible using (for example) the built-in helper function ones().

Step-through solution:

poly = ones(size(X,1),p  );
poly = poly .* X;
powers = 1:p;
poly = poly .^ powers;

One-liner:

poly = (ones(size(X,1),p) .* X) .^[1:p];

Upvotes: 1

Related Questions