[英]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. 令x为列向量。 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. 令x1,x2和x3为列向量让我们考虑第一个。 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] ? 但这也不起作用,因为这意味着取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. (即,所有1到x。^ 100之间的值都具有x差)因此,这也不能用于生成这样的矩阵。 Please consider x = [1; 请考虑x = [1; 2; 2; 3; 3; 4]; 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 - 使用此bsxfun
技术-
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]
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]
x = [1 2; 3 4; 5 6]
并且您希望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 - Y = [1 1 1 2 4; 1 3 9 4 16; 1 5 25 6 36]
即Y = [ 1 x1 x1.^2 x2 x2.^2 ]
对于列向量x1
, x2
...,您可以使用这种单线-
[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: 使用Matlabs vander()-Function中找到的代码的改编版(也可以在polyfit-function中找到),与Divakars不错的简短解决方案相比,如果您使用以下代码,则可以显着提高速度:
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]'
. 对于给定的示例,它的速度大约是它的两倍,如果我将N=50
设置N=50
x = [1:40]'
,它的速度大约是它的20倍。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.