如何在Matlab中进行矢量化?
我想向量化这两行代码。我最近刚刚了解矢量化。我知道如何矢量化 sumsurface 线,但我不确定如何包含 if 语句,我真的很想矢量化整个 for 循环并摆脱它。我想矢量化以改善运行时间,我现在的代码运行速度非常慢。我预先分配了数组,这有助于提高运行时间。我之前忘记这样做了。如果我能得到任何帮助,我将不胜感激。
pH = linspace(2,12, 6000);
for j = 1:300
nAsp = randi([10, 30],[1,1]);%865
nGlu = randi([12, 38],[1,1]);%1074
nLys = randi([11, 33],[1,1]);%930
nArg = randi([10, 30],[1,1]);%879
nCys = randi([2, 8],[1,1]); %214
nTyr = randi([5, 17],[1,1]); %462
nHis = randi([4, 12],[1,1]); %360
for i = 1: len;
sumsurface(i) = (nAsp).*(-(10.^((pH(i)-asp) )./(10.^((pH(i)-asp) )+1)) )+ (nGlu).*(-(10.^((pH(i)-glu) )./(10.^((pH(i)-glu) )+1)))+(nCys).*(-(10.^((pH(i)-cys) )./(10.^((pH(i)-cys) )+1)))+ (nTyr).* (-(10.^((pH(i)-tyr) )./(10.^((pH(i)-tyr) )+1)))+ (nHis).*(1./(10.^((pH(i)-his) )+1))+ (nLys).*(1./(10.^((pH(i)-lys) )+1))+ (nArg).*(1/(10.^((pH(i)-arg) )+1));
if sumsurface(i) < .01 && sumsurface(i) > -.01
%disp(sumsurface(i));
disp(pH(i));
x(1+end) = pH(i);
aspl(1+end) = nAsp;
glul(1+end) = nGlu;
cysl(1+end) = nCys;
tyrl(1+end) = nTyr;
hisl(1+end) = nHis;
lysl(1+end) = nLys;
argl(1+end) = nArg;
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以对整个算法进行矢量化。我不会为您全部编写代码,但这里有一些指导您入门:
pH
副本,即len
。n
开头的变量从标量更改为向量。例如,nAsp = randi([10, 30], [len, 1])
sumsurface
索引,即index = find(sumsurface < 0.01 & sumsurface >-0.01);
。index
创建所需的向量,例如aspl = nAsp(index);
You can vectorize the whole algorithm. I'm not going to code it all out for you but here are some pointers to get you started:
pH
as there are iterations, i.e.len
.n
from scalars to vectors. For example,nAsp = randi([10, 30], [len, 1])
sumsurface
that match your criteria, i.e.index = find(sumsurface < 0.01 & sumsurface > -0.01);
.index
, e.g.aspl = nAsp(index);
以下是一种可能的向量化:
运行代码后,元胞数组
x
和p
将包含每次迭代的pH
和 < code>params 分别满足您的方程:-0.01(如果存在)。
Here is one possible vectorization:
After running the code, the cell-arrays
x
andp
will contain, for each iteration, thepH
andparams
respectively that satisfy your equation:-0.01<sumsurface<0.01
(if they exist).