ycagelulu
ycagelulu

Reputation: 15

How to generate a matrix automatically with given n in matlab

For the linear regression, I want to generate the matrix for polynomials of n degree.

if n is 1

X=[x(:), ones(length(x),1)]

if n is 2

X=[x(:).^2 x(:) ones(length(x),1)]

...

if n is 5

X=[x(:).^5 x(:).^4 x(:).^3 x(:).^2 x(:) ones(length(x),1)]

I do not know how to code with matlab if I set n=6 and it will automatically generate the wanted X matrix. Hope you can help me.

Upvotes: 0

Views: 104

Answers (3)

Nicky Mattsson
Nicky Mattsson

Reputation: 3052

If you write edit polyfit you can see how MATLAB have implemented the polyfit command, which is similar to what you are trying to do. In there you will find the code

% Construct the Vandermonde matrix V = [x.^n ... x.^2 x ones(size(x))]
V(:,n+1) = ones(length(x),1,class(x));
for j = n:-1:1
    V(:,j) = x.*V(:,j+1);
end

Which constructs the matrix you are interested in. The benefit of this method over the bsxfun is that you only calculate x(:).^n and then saves the intermediary results. Instead of treating all powers as seperate problems, e.g. x(:)^(n-1) as a seperate problem to x(:).^n.

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112759

This can be easily done with bsxfun:

X = bsxfun(@power, x(:), n:-1:0);

Or, in Matlab versions from R1016b onwards, you can use implicit expansion:

X = x(:).^(n:-1:0);

Upvotes: 3

Justin Wager
Justin Wager

Reputation: 323

Check out the polyval function. I believe that will do what you’re looking for.

To get increasing the polynomial to increase in degree, you can increase the length of your p argument using a loop.

Upvotes: 0

Related Questions