I would like to implement a function very similar to the floor function, but instead of rounding towards the nearest integer, I would like it to round any number(s) according to a specified array, and I would like to code this in Matlab.
For example, I have a set of arbitrary array of numbers given by:
A = [-1.1778, 1.3657, 2.9880, -0.5674].
I then have a second array of integers as:
Q = [-3, -1, 1, 3].
I would like to each element of A as you would using the floor function, but they must round to one of the integers given in Q.
So A(3) = 2.9880 must be rounded to 1, since it is the largest integer in the given set Q that is smaller or equal to it. Likewise, A(1) = -1.1778 must be rounded to -3.
The closest I have come is rounding numbers according to a specific set, but I could not figure out how to round down or up, specifically.
My best attempt is shown below:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s_hat = roundSet(num_array, integer_set)
C = zeros(length(integer_set), length(num_array));
s_hat = zeros(1, length(num_array));
for ii = 1:length(num_array)
for jj = 1:length(integer_set)
C(jj, ii) = abs(num_array(ii) - integer_set(jj));
end
end
[~, i] = min(C, [], 1);
for ii = 1:length(i)
s_hat(ii) = integer_set(i(ii));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The code rounds numbers in a according to the nearest elements in b, but does not round up or down, it just rounds the numbers off. If I can solve this problem, I can also implement a similar that rounds up, like the ceiling function.
Any help would be greatly appreciated.
Thank you.