Let x=1:100
and N=1:10
. I would like to create a matrix x^N
so that the i
th 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?
Let x=1:100
and N=1:10
. I would like to create a matrix x^N
so that the i
th 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?
Sounds like a Vandermonde matrix. So use vander:
I'd go for:
Another solution (probably much more efficient):
Or even:
Hope this helps.
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
.^
:This creates an 11-by-100 matrix where each column
i
contains[i^0; i^1; i^2; ... i^10]
.Not sure if it really fits your question.
EDIT: As pointed out by Adrien, my first attempt was not compliant with the OP question.
Why not use an easy to understand for loop?
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.)