MATLAB: Error using floor() and ceil() for specific values between o and 1

ceilfloorMATLAB

Good afternoon,
I'm implementing a function that receive a value and look for this value inside of a matrix. The matrix have just integer values, but the value inside the function is not integer. To solve this problem i'm using the following idea:
%The function receive the value of beta;
%find the first index of the matrix that represents a bigger value
% (Ex: if beta is 8.5, try to find the index that gives the value 9)
index_beta_i_sup = find(Re_36e4 == ceil(beta)); %matrix
beta_i_sup = ceil(beta);
if isempty(index_beta_i_sup) %if the value of beta is not found, I increment +1 until find it
while isempty(index_beta_i_sup)
beta_i_sup = beta_i_sup+1;
index_beta_i_sup = find(Re_36e4 == beta_i_sup);
end
end
The same idea to try to find the lower index value inside the matrix:
index_beta_i_inf = find(Re_36e4 == floor(beta));
beta_i_inf = floor(beta);
if isempty(index_beta_i_inf)
while isempty(index_beta_i_inf)
beta_i_inf = beta_i_inf-1;
index_beta_i_inf = find(Re_36e4 == beta_i_inf);
end
end
When I run the problem using values: 1 < beta < 180 the function works perfectly.I put some prints to check if I run the code with beta <1, the following error appear.
beta= 8.700000e-01;
beta_sup= 1;
index_beta_i_sup = 53 %(inside the matrix - OK)

beta= 8.700000e-01;
beta_inf= 0;
index_beta_i_inf = 52 %(inside the matrix - OK)
| _*%this part is not suppose to be here in the code!*_|
*beta= 104;
beta_inf= 155;
index_beta_i_inf = 206*
Error: Index exceeds matrix dimensions.
My matrix has no 206 elements, that's why I have problem, but i didn't intend to make this last calculation, appear alone *(this beta=104). The problem is just for floor().
If I use the value of beta=-0.87, the problem will be in the ceil() function, that will return this beta=104.
Thanks for your support.

Best Answer

I'm not too clear on what the problem exactly is, but, if you're trying to find the nearest number above or below your input in the matrix, using a loop over the integers is ... very wasteful.
How about:
%inputs: Re_36e4, a matrix (what an odd and meaningless name for a variable!)
%beta: a number.
%find nearest number above beta
tempRe = Re; %copy Re_36e4 if you don't want to modify it

tempRe(tempRe < beta) = Inf; %replace any number below beta by +Inf
[beta_i_sup, index_beta_i_sup] = min(tempRe(:));
%note that if beta_i_sup is inf, then there was no number above beta
%find nearest number below beta
tempRe = Re; %copy Re_36e4 if you don't want to modify it
tempRe(tempRe > beta) = -Inf; %replace any number above beta by -Inf
[beta_i_inf, index_beta_i_inf] = max(tempRe(:));
%note that if beta_i_inf is -inf, then there was no number below beta
The matrix does not even have to be integer for the above to work.