简体   繁体   中英

Creating Matrix with a loop in Matlab

I want to create a matrix of the following form

    Y = [1 x x.^2 x.^3 x.^4 x.^5 ... x.^100]

Let x be a column vector. or even some more variants such as

    Y = [1 x1 x2 x3 (x1).^2 (x2).^2 (x3).^2 (x1.x2) (x2.x3) (x3.x1)]

Let x1,x2 and x3 be column vectors Let us consider the first one. I tried using something like

    Y = [1 : x : x.^100]

But this also didn't work because it means take Y = [1 x 2.*x 3.*x ... x.^100] ? (ie all values between 1 to x.^100 with difference x) So, this also cannot be used to generate such a matrix. Please consider x = [1; 2; 3; 4]; and suggest a way to generate this matrix

    Y = [1 1 1 1 1;
         1 2 4 8 16;
         1 3 9 27 81;
         1 4 16 64 256];

without manually having to write

    Y = [ones(size(x,1)) x x.^2 x.^3 x.^4]

Use this bsxfun technique -

N = 5; %// Number of columns needed in output
x = [1; 2; 3; 4]; %// or [1:4]'
Y = bsxfun(@power,x,[0:N-1])

Output -

Y =
     1     1     1     1     1
     1     2     4     8    16
     1     3     9    27    81
     1     4    16    64   256

If you have x = [1 2; 3 4; 5 6] x = [1 2; 3 4; 5 6] x = [1 2; 3 4; 5 6] and you want Y = [1 1 1 2 4; 1 3 9 4 16; 1 5 25 6 36] Y = [1 1 1 2 4; 1 3 9 4 16; 1 5 25 6 36] Y = [1 1 1 2 4; 1 3 9 4 16; 1 5 25 6 36] ie Y = [ 1 x1 x1.^2 x2 x2.^2 ] for column vectors x1 , x2 ..., you can use this one-liner -

[ones(size(x,1),1) reshape(bsxfun(@power,permute(x,[1 3 2]),1:2),size(x,1),[])]

Using an adapted Version of the code found in Matlabs vander()-Function (which is also to be found in the polyfit-function) one can get a significant speedup compared to Divakars nice and short solution if you use something like this:

N = 5;
x = [1:4]';
V(:,n+1) = ones(length(x),1);
for j = n:-1:1
   V(:,j) = x.*V(:,j+1);
end
V = V(:,end:-1:1);

It is about twice as fast for the example given and it gets about 20 times as fast if i set N=50 and x = [1:40]' . Although I state that is not easy to compare the times, just as an option if speed is an issue, you might have a look at this solution.

in octave, broadcasting allows to write

N=5;
x = [1; 2; 3; 4];
y = x.^(0:N-1)

output -

y =

     1     1     1     1     1
     1     2     4     8    16
     1     3     9    27    81
     1     4    16    64   256

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