我写了一段代码,生成一个长度递增的向量,然后将其堆叠在一个矩阵中,一行接着一行。这是代码如何工作的示例
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我如何向量化这个循环?
发布于 2013-03-29 10:47:15
这是一个完全矢量化的构建矩阵的方法--没有循环,没有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为了清楚起见,我使用了一堆临时变量。如果你想避免弄乱你的工作区,你可以避免使用它们,因为它们通常不会被多次使用。
另请注意:这将在您未指定任何其他值的情况下使用NaNs填充矩阵。如果您希望将这些替换为其他默认值(例如,0或1),则在最后执行此操作非常简单。
发布于 2013-03-29 08:33:56
这是矢量化的代码。我仍然不得不使用ARRAYFUN。所以用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;https://stackoverflow.com/questions/15693379
复制相似问题