Clear Filters
Clear Filters

Placing a number to regularly increasing array

1 view (last 30 days)
Hi everyone,
I have very basic problem but I can't deal with it. I have an array that regulary increasing e.g. 1,2,3,4,5..,10. I want to write a function that take decimal or integer number as input and determines that this number's place in that array. For example I wrote 3.2 as input and the function that I'll write should determine this number is between 3 and 4. Is there any function do the same thing? If not, how can I solve this? Any thoughts?
Thanks in advance.

Answers (1)

Navdha Agarwal
Navdha Agarwal on 21 Jun 2019
I hope the following snippet help you.
a = 1:10;
insert = 3.2;
for i = 1:length(a)
if( i == 1 && insert <= a(i)) % if the element to be inserted is smaller than the first element of the array
b = [insert a];
break;
elseif( insert >= a(i) && insert <=a(i+1)) % if the element to be inserted is in between the array
b = [a(1:i) insert a(i+1:end)];
break;
else % if the element to be inserted is greater than all the elements in the array and is inserted at the end
b = [a insert];
break;
end
end
disp(b)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!