Question

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. For example:

X is equal to 9 and the dxcp array is: [ 1, 2, 3, 6, 10, 20]. The second line would change X to be equal to 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. 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.

Was it helpful?

Solution

You need to use bsxfun to extend your case to a vector case.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top