function av = vlookup(a,b,bv)
% corresponds to Excels vlookup function, where a is the variable to lookup
% and cat(2, b, bv) corresponds to the (2-column) lookup table. a,b, and bv
% are vectors
av=NaN(size(a));
a=a(:);

if size(b,2)~=1 | size(bv,2)~=1
    error('b and bv must be vectors')
end
if length(b)~=length(bv)
    error('b and bv must have the same length')
end

% eliminate identical rows
%(to prevent the following error message from showing up unneccessarily):
[b, ix]=sort(b); bv=bv(ix);
doublerow=cat(1, false, b(2:end)==b(1:end-1) & bv(2:end)==bv(1:end-1));
b(doublerow)=[]; bv(doublerow)=[];

if       (length(b(ismember(b,a))) ~= length(unique(b(ismember(b,a)))));
    delta=length(b(ismember(b,a))) -  length(unique(b(ismember(b,a))));    
    error(['Some lookup values in vector a are contained more than once in vector b. Vector lengths differ by ' num2str(delta) ' observations, or ' num2str(delta*100 / length(b(ismember(b,a))))  ' percent.'])
end

[ia, ib] = ismember(a, b);

avtmp=NaN(size(a));
avtmp(ia)=bv(ib(ib~=0));
av(:)=avtmp;
