Mic*_*ael 4 matlab for-loop matrix
我正在尝试创建一个如下所示的矩阵:
[1 x x^2 x^3 x^4 x^5]
[1 y y^2 y^3 y^4 y^5]
[1 z z^2 z^3 z^4 z^5]
Run Code Online (Sandbox Code Playgroud)
等等.将具有x,y,z,k等基本值的矩阵是Orig:
Orig = [ x y z k];
Run Code Online (Sandbox Code Playgroud)
我的起始矩阵将是
A = [1 x x^2 x^3 x^4 x^5];
Run Code Online (Sandbox Code Playgroud)
我的下一行代码是
for i=(2:10)
A(i)=A(i)^A(:,i)
end
Run Code Online (Sandbox Code Playgroud)
这个for循环正确地改变了每行需要提升的功率,但是它不会转到我的Orig矩阵中的下一个值.
所以基本上,我需要告诉Matlab在for循环中停止使用Orig(1,1)并转到Orig(1,2)第2行.
你可以用双循环来做到这一点
Orig = [x y z k];
exponent = [0 1 2 3 4 5];
%# preassign output to speed up loop
output = zeros(length(Orig),length(exponent));
%# loop over all elements in Orig
for r = 1:length(Orig)
%# loop over all exponents
for c = 1:length(exponent)
output(r,c) = Orig(r)^exponent(c);
end
end
Run Code Online (Sandbox Code Playgroud)
但是,这不是您通常在Matlab中编程的方式.
相反,你会复制这两个Orig和exponent,并做计算于一体,向量操作:
%# transpose orig so that it is a n-by-1 array
repOrig = repmat(Orig',1,length(exponent); %'#
repExp = repmat(exponent,length(Orig),1);
%# perform the exponent operation in one go
output = repOrig .^ repExp; %# note the ".", it applies operations element-wise
Run Code Online (Sandbox Code Playgroud)
几年以来,有一个快捷版本,使用函数bsxfun.这将自动执行我们上面所做的扩展repmat,并且会更快.
output = bsxfun(@power, Orig', exponent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1837 次 |
| 最近记录: |