How to find the closest lower value in a vector, given a specific value

4 views (last 30 days)
Hello,
I am wondering if there is the possibility to find the closest value lower in a vector, given a specific value.
For example I have a vector:
A = [.........4.9978e5 5.0001e5.........]
C = input('Assign highest allowed pressure: ') (In this example 5.0000e5)
I would then like MATLAB to find 4.9978e5 and also give me the index for the specific value as that index number will be used to find a specific element in another vector.
It could be seen like this, A is a vector for pressure at different water levels. C is the maximum allowed pressure. The point of this exercise is to find the water level given a maximum allowed pressure.
So far I've done like this:
Diff = abs(A - C);
[Min_Diff, Element_Min_Diff] = min(Diff);
Water_level_C = D(Element_Min_Diff);
disp('Maximum water level for highest allowed hydrostatic pressure: ')
disp(Water_level_C)
But what I want is for the program to choose the element 4.9978e5 rather than 5.0001e5 which is in reality closest to the given C. Because if the program chooses 5.0001e5 it will actually exceed the highest allowed pressure.
Also is there the possibility to somehow create a loop that continues asking for a new C until the user chooses to stop the loop?
Would this work?
Answer = 'Yes' %Creating the variable Answer
If Answer = 'Yes'
C = input('Assign highest allowed hydrostatic pressure: ');
Diff = abs(A - C);
[Min_Diff, Element_Min_Diff] = min(Diff);
Water_level_C = D(Element_Min_Diff);
disp('Maximum water level for highest allowed hydrostatic pressure: ')
disp(Water_level_C)
Answer = input('Would you like to try again with another value for hydrostatic pressure (Yes/No)?', 's')
end
Oh, and one last thing. How can I write so that the two disps in my code actually become only one and is shown on the same line?
Appreciate any help given.
Thank you in advance!

Answers (1)

Walter Roberson
Walter Roberson on 6 Dec 2013
To show multiple pieces of information on the same line, use fprintf() instead of disp()
To find the table value no greater than a test value,
Table_Values = [ ... 4.9978e5 5.0001e5 ... ];
[counts, idx] = histc(C, Table_Values);
Value_from_table = Table_Values(idx);
difference_from_table = C - Value_from_table;

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!