简体   繁体   中英

Creating a vector in MATLAB with a pattern

How do I create a vector like this:

a = [a_1;a_2;...,a_n]; 
aNew = [a;a.^2;a.^3;...;a.^T].

Is it possible to create aNew without a loop?

So you want different powers of a, all strung out into a vector? I would create an array, where each column of the array is a different power of a. Then string it out into a vector. Something like this...

aNew = bsxfun(@power,a,1:T);
aNew = aNew(:);

This does what you want, in a simple, efficient way. bsxfun is a more efficient way of writing the expansion than are other methods, such as repmat, ndgrid and meshgrid.

The code I wrote does assume that a is a column vector, as you have constructed it.

The idea is to use meshgrid to create two arrays of size nx T :

[n_mesh, t_mesh] = meshgrid(a, 1:T);

Now n_mesh is an array where each row is a duplicate of a , and t_mesh is an array where each column is 1:T .

Now you can use an element-wise operation on them to create what you need:

aNew = n_mesh .^ t_mesh;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM