Vectorizing the creation of a matrix of successive

2020-02-01 18:27发布

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?

5条回答
甜甜的少女心
2楼-- · 2020-02-01 18:52

Sounds like a Vandermonde matrix. So use vander:

A = vander(1:100);
A = A(1:10, :);
查看更多
家丑人穷心不美
3楼-- · 2020-02-01 18:53

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.

查看更多
做自己的国王
4楼-- · 2020-02-01 18:54

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

查看更多
Viruses.
5楼-- · 2020-02-01 18:55

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))];
查看更多
小情绪 Triste *
6楼-- · 2020-02-01 19:00

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

查看更多
登录 后发表回答