Ryan
Ryan

Reputation: 53

Rounding to user-defined number in matlab

I have a problem with rounding to user defined numbers.

I have a MxN matrix with different numbers between -3 and 12.

And then I have to round each number in the matrix to the nearst of [-3,0,2,4,7,10,12] I have red some about the rounding and floor function, but can't figure out how to round towards a specific number.

Upvotes: 2

Views: 59

Answers (2)

CKT
CKT

Reputation: 781

It sounds like what you want is the discretize function:

>> % The set of values
>> setValues = [-3 0 2 4 7 10 12]';
>> % Find the midpoints between values to set as bin edges
>> binEdges = 0.5*(setValues(1:(end-1)) + setValues(2:end));
>> % Test a whole range of values
>> A = (-3.5:0.5:12.5)';
>> % Use discretize and include edges at -Inf and Inf to
>> % make sure we have the right # of bins
>> D = setValues(discretize(A, [-Inf; binEdges; Inf]));
>> % Compare the original values with the discretized version.
>> [A D]

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112679

Use interp1 with the 'nearest' option:

x = [-2.1, 1.5; 5.7, 10.8]; % data values
y = [-3, 0, 2, 4, 7, 10, 12]; % allowed values
result = interp1(y,y,x,'nearest');

This gives

result =
    -3     2
     7    10

If you prefer to do it manually: compute all pairwise absolute differences, find the minimizing index for each data value, and index into the matrix of allowed values:

[~, ind] = min(abs(bsxfun(@minus, x(:).',y(:))), [], 1);
result = reshape(y(ind), size(x));

Upvotes: 2

Related Questions