Is there a function in MATLAB 7.6 (R2008a) equal to VLOOKUP in Excel?

6 views (last 30 days)
I would like to know if there exists a function in MATLAB that is equivalent to the VLOOKUP function in Excel.
I have created the following matrix in MATLAB:
mydata=[datenum('1/31/2008') 3; datenum('2/28/2008') 5];
I would like to search for a lookup_value in the first column of an array. If there exists a value in the first column of an array that is matching the lookup_value (exact match), then the function should return a value in the same row from another column in the array. If an exact match does not exists, the function should return the next largest value that is less than lookup_value.
For example, for the matrix above,
myMatch= fcm(mydata,datenum('2/7/2008'))
should output
myData=
3

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 14 Sep 2015
This functionality does not exist as a builtin command in MATLAB 7.6 (R2008a). However it can be easily implemented by, for example, this function:
% FCM find an exact or approximate match
%
% mData = fcm(mydata, lookup_value)
%
% Will return an exact or approximate match. If an exact match is not
% found, the next largest value that is less than lookup_value is returned.
function mData = fcm(data, lookup_value)
dist = abs(data(:,1)-lookup_value); % Find distance to numbers in list
[min_val, min_loc] = min(dist); % Find minimum value
if data(min_loc,1)<=lookup_value
mData = data(min_loc,2);
else
try
mData = data(min_loc-1,2);
catch ME
if ME.identifier=='MATLAB:badsubscript',
error('The lookup_value must be greater than the smallest value in 1st column of the lookup array'),end
mData=NaN;
end
end
This function returns an error if the lookup_value is smaller than the smallest number in the 1st column of the lookup array.
Note that if you are using the data type table you can achieve this kind of functionality by accessing the value via the row name ( T.Value('rowname')).

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2015a

Community Treasure Hunt

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

Start Hunting!