我一直试图从一个本科生为我们编写的代码中对一些操作进行矢量化处理。他使用了丑陋的嵌套循环,我尝试将其更改为bsxfun调用。当我按原样使用此函数时,此方法有效,但是当我尝试使用编码器进行混合编译时,出现错误。
编辑:我知道我应该澄清代码的某些部分。 S,W和N是nxn矩阵,指示成对比较ij的偏好。 mu是包含绝对评级重建的(预测)分数的行 vector 。
要检查代码的作用,您可能想检查页面的最底部。
原始代码如下:
for i = 1:n
for j = i:n
if i~= j
mu = x(i) - x(j);
md1 = normcdf(-delta1, mu); %minus d0
md0 = normcdf(-delta0, mu);
d0 = normcdf( delta0, mu);
d1 = normcdf( delta1, mu);
Y = Y + S(i,j) .* log(1 - d1) + ...
W(i,j) .* log(d1 - d0) + ...
N(i,j) .* log(d0 - md0) + ...
W(j,i) .* log(md0 - md1) + ...
S(j,i) .* log(md1);
end
end
end
Y = -Y; %this will be used in fminsearch, therefore the negative sign
我为此编写了一个快速而肮脏的矢量化解决方案:
diffs = bsxfun(@minus,x,x');
% create the deltas array augmented by -Inf and Inf for easy diff calculation
deltass = sort([-Inf, Inf, deltas, -1*deltas]);
deltass = reshape(deltass, [1, 1, length(deltass)]);
normcdfs = diff(1-bsxfun(@normcdfupper, diffs, deltass), 1, 3);
normcdfs(repmat(logical(tril(ones(size(normcdfs(:,:,1))))),[1,1,length(deltass)-1])) = 1;
Y = -sum(sum(sum(normcdfs_input.*log(normcdfs))));
编辑:normcdfupper是我编写的包装类,自从我遇到问题以来,我就调用normcdf(diff,delta,'upper'),该末端可能导致错误。
现在就像我说的那样,这在我的日常使用中很好用。但是由于混合了旧的嵌套for循环版本带来了巨大的加速,所以我尝试使用此加速版本进行相同的操作,仅在编码器中遇到以下错误:
Expansion is only supported along dimensions where one input argument or the other has a fixed length of 1.
Error in lik_ml (line 27)
normcdfs = diff(1-bsxfun(@normcdfupper,diffs,deltass),1,3);
diffs是:infx:inf double ,而deltass是1x1x:inf double 。编码器告诉我:
diffs
deltass
如果有人可以帮助我解决此错误消息,我将不胜感激。
编辑:一些代码对其进行测试:
clear all;
% rng(322);
delta0 = 1;
delta1 = 2;
deltas = [delta0, delta1];
sigma = 0.5;
options = 5;
maxVotes = 10000;
voteStep = 3;
initialVoteStep = 3;
raw_mu = rand(1,options);
mu = sort(zscore(raw_mu));
S = zeros(options);
W = zeros(options);
N = zeros(options);
for i = 1:options
for j = i:options
if i ~= j
S(i,j) = 1 - normcdf(delta1, mu(i)-mu(j));
W(i,j) = normcdf( delta1, mu(i)-mu(j)) - normcdf( delta0, mu(i)-mu(j));
N(i,j) = normcdf( delta0, mu(i)-mu(j)) - normcdf(-delta0, mu(i)-mu(j));
W(j,i) = normcdf(-delta0, mu(i)-mu(j)) - normcdf(-delta1, mu(i)-mu(j));
S(j,i) = normcdf(-delta1, mu(i)-mu(j));
end
end
end
diffs = bsxfun(@minus,mu,mu');
deltass = sort([-Inf, Inf, deltas, -1*deltas]);
deltass = reshape(deltass,[1,1,length(deltass)]);
normcdfs = diff(bsxfun(@(x,y) normcdf(y,x),diffs,deltass),1,3);
最佳答案
这是for循环的向量化版本
[I,J] = meshgrid(1:n);
idx = I<J;
I = I(idx);
J = J(idx);
IJ = sub2ind([n n],I,J);
JI = sub2ind([n n],J,I);
mu = x(I)-x(J);
md1 = normcdf(-delta1, mu).';
md0 = normcdf(-delta0, mu).';
d0 = normcdf( delta0, mu).';
d1 = normcdf( delta1, mu).';
Y = sum(S(IJ) .* log(max(0,1 - d1)) + ...
W(IJ) .* log(max(0,d1 - d0)) + ...
N(IJ) .* log(max(0,d0 - md0)) + ...
W(JI) .* log(max(0,md0 - md1)) + ...
S(JI) .* log(max(0,md1)));
关于matlab - Matlab编码器导致bsxfun中的矩阵扩展问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40854836/