Selecting elements closest to zero

Viewed 81

Let's say I have a vector A = [-3 -2 -1 1 2]. I want to pick out the positive element closest to zero and the negative element closest to zero while retaining their index value in the vector A. So I want another vector with [-1, 4; 1,5] (i.e. [-ve to 0, index ; +ve to 0, index]).

I've tried creating separate arrays with the positive and negative components and selecting the min/max of these, but this loses the index in A. E.g.

Ap = A(A>0)
An = A(A<0)
 [ap,idxp]=sort(Ap)
 [an,idxn]=sort(An)

I'm sure there must be a simple way to do this. Any help greatly appreciated.

3 Answers

Invert the vector

B = 1 ./ A;

and find min

[~, idxn] = min(B);
an = A(idxn);

and max

[~, idxp] = max(B);
ap = A(idxp);

You can keep the index with

Ap = A;
Ap(Ap < 0) = NaN;
[ap,idxp] = min(Ap);
An = A;
An(An > 0) = NaN;
[an,idxn] = max(An);

You can sort the absolute values, then pick out the indices and values of the first value where A is greater than or less than zero:

A = [-3 -2 -1 1 2];
[sA,idx] = sort(abs(A)); % Sort absolute values to get closest to 0 order
idxP = idx( find( A(idx) > 0, 1 ) ); % First index where sorted A is positive
idxN = idx( find( A(idx) < 0, 1 ) ); % First index where sorted A is negative

out = [A(idxP), idxP; A(idxN), idxN]; % Formatted output as requested: [1, 4; -1, 3] for example
Related