Placing a number to regularly increasing array
2 次查看(过去 30 天)
显示 更早的评论
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.
回答(1 个)
Navdha Agarwal
2019-6-21
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dialog Boxes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!