如何在Matlab中对循环进行矢量化?

如何在Matlab中对循环进行矢量化?,matlab,matrix,vectorization,Matlab,Matrix,Vectorization,我编写了一段代码,生成了一个长度不断增加的向量,该向量随后在矩阵中一行接一行地堆叠。这是代码工作原理的一个示例 PPR=[0 2 3 5 6 8]; AI=[ 0 0.7854 0.5236 0.3142 0.2618 0.1963]; for ii=1:numel(PPR); qp=0:PPR(ii); xp(ii,1:PPR(ii)+1)=sin(AI(ii)*qp

我编写了一段代码,生成了一个长度不断增加的向量,该向量随后在矩阵中一行接一行地堆叠。这是代码工作原理的一个示例

    PPR=[0     2     3     5     6     8];
    AI=[ 0    0.7854    0.5236    0.3142    0.2618    0.1963];

    for ii=1:numel(PPR);
        qp=0:PPR(ii);
        xp(ii,1:PPR(ii)+1)=sin(AI(ii)*qp)+1    
    end

如何将此循环矢量化?

以下是矢量化代码。我还得用一排排的。因此,如果tic/toc比您的循环快,请使用tic/toc进行测试

n = numel(PPR); % number of rows
m = max(PPR)+1; % number of columns
qp = arrayfun(@(x)[0:PPR(x) nan(1,m-PPR(x)-1)],1:n,'UniformOutput',0);
qp = vertcat(qp{:});
a = ~isnan(qp); % to add ones later
qp(~a) = 0;
xp = sin(bsxfun(@times,AI',qp)) + a;

这里有一种完全矢量化的方法来构造矩阵-没有循环,没有
arrayfun

PPR=[0     2     3     5     6     8];
AI=[ 0    0.7854    0.5236    0.3142    0.2618    0.1963];


M = ones(length(PPR),PPR(end)+1); #% allocate proper sized matrix of ones
r=1:length(PPR)-1; #% row indices for 1 element past the end of each row vector
c=PPR(1:end-1)+2; #% corresponding column indices
linear_index = sub2ind(size(M),r,c); #% create linear index from r,c
M(linear_index)=nan; #% set those elements to NaN
M2 = cumsum(M,2)-1; #% use cumsum to propagate the NaN values
M3 = bsxfun(@times,M2,AI'); #%'#multiply each row by the appropriate AI value
xp = sin(M3)+1 #% take the sine of the matrix
为了清晰起见,我使用了一些临时变量。如果您想避免工作区混乱,您可以避免它们,因为它们通常不会被多次使用


另请注意:这将使用未指定任何其他值的NAN填充矩阵。如果您希望用其他默认值(例如,0或1)替换这些值,这在最后非常简单。

是否因为速度慢而要对其进行矢量化?如果是这样,您至少应该先尝试预分配,然后按列存储结果,因为matlab是column major.+1用于有趣的解决方案。特别是,它很酷。然而,我已经用tic/toc(2012b,win7)测试了所有3个代码,OP的循环代码是最好的(我的比预期的更糟)。JIT编译器正在工作。