简体   繁体   English

矢量化从一个单独的矢量中减去多个矢量

[英]Vectorizing the subtraction of multiple vectors from one individual vector

I am trying to vectorize, or make the following code more efficient: 我正在尝试向量化,或使以下代码更有效:

[Y,k] = min(abs(dxcp-X));
X = dxcp(k);

The objective of the code is to compare a value X to an array of accepted values for x (dxcp) and assign X to the closest value in the array dxcp. 代码的目标是将值X与x(dxcp)的可接受值数组进行比较,并将X分配给数组dxcp中的最接近值。 For example: 例如:

X is equal to 9 and the dxcp array is: [ 1, 2, 3, 6, 10, 20]. X等于9,dxcp数组为:[1,2,3,6,10,20]。 The second line would change X to be equal to 10. 第二行将X更改为等于10。

I am trying to change my script so that X can be inputted as an array of numbers and was wondering what would be the most efficient way to go about making the above code work for this case. 我试图更改我的脚本,以便X可以作为一个数字数组输入,并想知道什么是最有效的方法来使上述代码适用于这种情况。 Of course I could use: 我当然可以用:

for i = 1:numel(X)
   [Y,k] = min(abs(dxcp-X(i)));
   X(i) = dxcp(k);
end

But I have the feeling that there must be a way to accomplish this more efficiently. 但我觉得必须有一种方法可以更有效地完成这项工作。 Cheers, nzbru. 干杯,nzbru。

You need to use bsxfun to extend your case to a vector case. 您需要使用bsxfun将案例扩展到矢量案例。

Code

dxcp = [1 2 3 6 10 20];
X = [2 5 9 18]

abs_diff_vals = abs(bsxfun(@minus,dxcp,X')); %%//'
[~,k] = min(abs_diff_vals,[],2);
X = dxcp(k)

Output 产量

X =
     2     5     9    18

X =
     2     6    10    20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM