MATLAB Answers

How to find the element of a number if that number were to be placed in an ordered list?

2 views (last 30 days)
arthurk
arthurk on 22 Feb 2020
Commented: arthurk on 22 Feb 2020
For example:
list = (0:10)
number= 2.5
the element it is in-between is 3 and 4
What is the most efficient way of finding where 2.5 would lie in that list and which elements it would be in-between?
Is there a better way than doing a for loop?
for i = 1:length(list)
if number > list(length(list))
fprintf('it is greater than any the numbers')
end
if number == list(i)
fprintf('it is element %d',i)
end
if number < list(length(list))
if number > list(i)
if number < list(i+1)
fprintf('it is between element %d and %d ',i,i+1 )
end
end
end
end

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 22 Feb 2020
The robust solution:
>> ida = find(list<number,1,'last')
ida = 3
>> idb = find(list>number,1,'first')
idb = 4

  0 Comments

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 22 Feb 2020
Between = [find(ismember(list1,fix(2.5))), find(ismember(list1,ceil(2.5)))]

  5 Comments

Show 2 older comments
Stephen Cobeldick
Stephen Cobeldick on 22 Feb 2020
Note that this will not work if the list does not contain the rounded number, e.g.:
>> list = 0:2:10
list =
0 2 4 6 8 10
>> number = 2.5;
>> find(ismember(list,fix(2.5)))
ans = 2
>> find(ismember(list,ceil(2.5))) % !!!!
ans = []
arthurk
arthurk on 22 Feb 2020
I'm trying to find the most efficient way. As you can see from my code I do have knowledge of using operators, however I'm trying to make it efficiently as possible without expending many lines of code.

Sign in to comment.

Sign in to answer this question.

Tags

Products


Release

R2019b

Translated by