Vectorizing the creation of a matrix of successive powers

后端 未结 5 442
长情又很酷
长情又很酷 2020-12-07 00:47

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

相关标签:
5条回答
  • 2020-12-07 01:24

    Not sure if it really fits your question.

    bsxfun(@power, cumsum(ones(100,10),2), cumsum(ones(100,10),1))
    

    EDIT: As pointed out by Adrien, my first attempt was not compliant with the OP question.

    xn = 100;
    N=10;
    solution = [ones(1,xn); bsxfun(@power, cumsum(ones(N,xn),2), cumsum(ones(N,xn),1))];
    
    0 讨论(0)
  • 2020-12-07 01:28

    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].

    0 讨论(0)
  • 2020-12-07 01:34

    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.

    0 讨论(0)
  • 2020-12-07 01:35

    Sounds like a Vandermonde matrix. So use vander:

    A = vander(1:100);
    A = A(1:10, :);
    
    0 讨论(0)
  • 2020-12-07 01:35

    Why not use an easy to understand for loop?

    c = [1:10]'; %count to 100 for full scale problem
    for i = 1:4; %loop to 10 for full scale problem
        M(:,i) = c.^(i-1)
    end
    

    It takes more thinking to understand the clever vectorized versions of this code that people have shown. Mine is more of a barbarian way of doing things, but anyone reading it will understand it.

    I prefer easy to understand code.

    (yes, I could have pre-allocated. Not worth the lowered clarity for small cases like this.)

    0 讨论(0)
提交回复
热议问题