2011-07-12 218 views
0

我想向量化这两行代码。我最近才了解了矢量化。我知道如何矢量化sumsurface行,但我不知道如何包含if语句,我真的想要矢量化整个for循环并摆脱它。我想要矢量化以改善运行时我现在运行的代码运行速度非常慢。我预先分配了有助于改进运行时的数组。我以前忘了这么做。如果我能得到任何帮助,将不胜感激。如何在Matlab中进行矢量化?

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 

回答

1

这里是一个可能的矢量:

%# data 
len = 6000; 
pH = linspace(2,12, len); 

%# some constants (fill your values here) 
asp = 0; glu = 0; cys = 0; tyr = 0; his = 0; lys = 0; arg = 0; 

%# random parameters for each iteration 
num = 300; 
nAsp = randi([10 30], [num 1]); 
nGlu = randi([12 38], [num 1]); 
nLys = randi([11 33], [num 1]); 
nArg = randi([10 30], [num 1]); 
nCys = randi([2 8] , [num 1]); 
nTyr = randi([5 17] , [num 1]); 
nHis = randi([4 12] , [num 1]); 

params = [nAsp nGlu nCys nTyr nHis nLys nArg]; 
M = [ 
    - 10.^(pH-asp) ./ (1 + 10.^(pH-asp)) 
    - 10.^(pH-glu) ./ (1 + 10.^(pH-glu)) 
    - 10.^(pH-cys) ./ (1 + 10.^(pH-cys)) 
    - 10.^(pH-tyr) ./ (1 + 10.^(pH-tyr)) 
    1 ./ (1 + 10.^(pH-his)) 
    1 ./ (1 + 10.^(pH-lys)) 
    1 ./ (1 + 10.^(pH-arg)) 
]; 

%# iterations 
sumsurface = zeros(num,len); 
x = cell(num,1); p = cell(num,1); 
for j=1:num 
    sumsurface(j,:) = params(j,:)*M; 

    idx = abs(sumsurface(j,:)) < 0.01; 
    if any(idx) 
     x{j} = pH(idx); 
     p{j} = params(j,:); %# [aspl glul cysl tyrl hisl lysl argl] 
    end 
end 

运行代码后,将细胞阵列xp将包含,对于每次迭代,满足您的方程pHparams分别为:-0.01<sumsurface<0.01(如果它们存在)。

3

您可以矢量化整个算法。我不会把它所有的代码为你,但这里有一些提示,让你开始:

  • 使用REPMAT创建因为有重复,它包含pH多个副本的阵列,即len
  • 将从n开始的所有变量从标量更改为向量。例如,nAsp = randi([10, 30], [len, 1])
  • 使用FIND来确定符合您的标准的sumsurface的索引,即index = find(sumsurface < 0.01 & sumsurface > -0.01);
  • 使用index创建您想要的矢量,例如, aspl = nAsp(index);
  • 冲洗。重复。
+0

我更新了我的代码,我意识到我忽略了一个重要部分。我有一个双循环,但矢量的长度是不同的。我不想让pH矢量与nAsp = randi([10,30],[len,1])矢量的长度相同。它仍然可以矢量化这个吗?感谢指针 –