FabianG
FabianG

Reputation: 73

Expand a matrix with polynomials

Say I have a matrix A with 3 columns c1, c2 and c3.

1 2 9
3 0 7
3 1 4

And I want a new matrix of dimension (3x3n) in which the first column is c1, the second column is c1^2, the n column is c1^n, the n+1 column is c2, the n+2 column is c2^2 and so on. Is there a quickly way to do this in MATLAB?

Upvotes: 4

Views: 492

Answers (3)

Cyrgo
Cyrgo

Reputation: 31

Try the following (don't have access to Matlab right now), it should work

    A = [1 2 9; 3 0 7; 3 1 4];
    B = [];
    for i=1:n
         B = [B  A.^i];
    end
    B = [B(:,1:3:end)  B(:,2:3:end)  B(:,3:3:end)];
    

More memory efficient routine:

    A = [1 2 9; 3 0 7; 3 1 4];
    B = zeros(3,3*n);
    for i=1:n
         B(3*(i-1)+1:3*(i-1)+3,:) = A.^i;
    end
    B = [B(:,1:3:end)  B(:,2:3:end)  B(:,3:3:end)];
    

Upvotes: 1

Jonas
Jonas

Reputation: 74930

Combining PERMUTE, BSXFUN, and RESHAPE, you can do this quite easily such that it works for any size of A. I have separated the instructions for clarity, you can combine them into one line if you want.

n = 2;
A = [1 2 9; 3 0 7; 3 1 4];
[r,c] = size(A);

%# reshape A into a r-by-1-by-c array
A = permute(A,[1 3 2]);

%# create a r-by-n-by-c array with the powers
A = bsxfun(@power,A,1:n);

%# reshape such that we get a r-by-n*c array
A = reshape(A,r,[])

A =

     1     1     2     4     9    81
     3     9     0     0     7    49
     3     9     1     1     4    16

Upvotes: 3

Colin T Bowers
Colin T Bowers

Reputation: 18530

Here is one solution:

n = 4;
A = [1 2 9; 3 0 7; 3 1 4];
Soln = [repmat(A(:, 1), 1, n).^(repmat(1:n, 3, 1)), ...
        repmat(A(:, 2), 1, n).^(repmat(1:n, 3, 1)), ...
        repmat(A(:, 3), 1, n).^(repmat(1:n, 3, 1))];

Upvotes: 0

Related Questions