如何在Matlab中进行矢量化?

时间:2011-07-12 04:58:47

标签: matlab vectorization

我想对这两行代码进行矢量化。我刚刚学会了矢量化。我知道如何矢量化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 

2 个答案:

答案 0 :(得分:3)

您可以对整个算法进行矢量化。我不打算为你编写代码,但这里有一些指导你的工作:

  • 使用REPMAT创建一个数组,其中包含与pH一样多的len副本,即n
  • 将所有以nAsp = randi([10, 30], [len, 1])开头的变量从标量更改为向量。例如,sumsurface
  • 使用FIND确定符合条件的index = find(sumsurface < 0.01 & sumsurface > -0.01);索引,即index
  • 使用aspl = nAsp(index);创建所需的向量,例如{{1}}
  • 冲洗。重复。

答案 1 :(得分: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:{{ 1}}(如果存在的话)。