2011-07-12 137 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])矢量的長度相同。它仍然可以矢量化這個嗎?感謝指針 –