MATLAB: Vectorise an n dimensional raise to the power loop

MATLAB: Vectorise an n dimensional raise to the power loop

power raise vector to vector n times

I am looking for the fastest way to compute the following
x = rand(1,1000);
for j = 1:m
for j = 1:n %etc.
phi(i,j,...) = ((x).^i).^j; %etc.
end
end
I have been looking at the bsxfun tool but it is restricted to a one-dimensional output.
Help would be gratefully appreciated, cheers.

Best Answer

  • You can call BSXFUN more than once:
    x = rand(1,1000);
    m = 30;
    n = 40;
    tic
    P1 = zeros(m,n,numel(x));
    for ii = 1:n
    for jj = 1:m
    P1(jj,ii,:) = x.^jj.^ii;
    end
    end
    toc
    tic
    P2 = bsxfun(@power, bsxfun(@power,permute(x,[3 1 2]),(1:m)'), 1:n);
    toc
    isequal(P1,P2)
  • Add a Comment

    Your email address will not be published. Required fields are marked *