Vectorizing the creation of a matrix of successive

2020-02-01 18:40发布

问题:

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 [1 i i^2 ... i^N].

I can easily do this using for loops. But is there a way to do this using vectorized code?

回答1:

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.



回答2:

Sounds like a Vandermonde matrix. So use vander:

A = vander(1:100);
A = A(1:10, :);


回答3:

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



回答4:

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))];


回答5:

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