4

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?

Jacob
  • 34,255
  • 14
  • 110
  • 165
FabianG
  • 73
  • 3

3 Answers3

3

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
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • I was just working on a general `bsxfun` solution when you posted this :-) I'll leave my answer as it stands as this is more elegant than what I'd come up with. +1. – Colin T Bowers Oct 07 '12 at 03:12
1

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)];
    
Cyrgo
  • 31
  • 2
  • `B` is growing inside the loop, which is very inefficient for large `n`. – Colin T Bowers Oct 07 '12 at 03:10
  • Inefficiency can be avoided by defining B = zeros(3,3*n) and by changing the line inside the loop to B(3*(i-1)+1:3*(i-1)+3,:) = A.^i; – Cyrgo Oct 07 '12 at 03:17
  • 1
    Agreed. But depending on level of experience, the OP may not realize this, so it would be best if you made it explicit in your answer. – Colin T Bowers Oct 07 '12 at 03:25
0

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))];
Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89