MATLAB: How to get the index from a matrix

indexing

Hi. I have a problem where I need to update the index value with a larger index if elements in A greater than B..
A = [2;7.5;9;10.5;15;14]; % Also can be in random numbers A and B are different in size
B = 5:5:50 % Fixed numbers
idx = ones(size(A,1),1; % Set to one if A less than B
for i = 1:size(A,1)
[~,idx(i)] = ismembertol(A(i),B,0.05);
end
% Results
idx = [0;1;2;2;3;3]
%Which I want to get
idx = [1;2;2,3,4,3]
Please help, and thanks in advance.

Best Answer

Assuming B is in ascending order, idx(i) contains the index value of B that is closest to but not less than A(i).
A = [2;7.5;9;10.5;15;14];
B = 5:5:50;
[~, idx] = max(A(:)'<B(:),[],1)
idx = 1×6
1 2 2 3 4 3
If it cannot be assumed that B is in ascending order,
A = [2;7.5;9;10.5;15;14];
B = [5, 15, 10, 20:5:50]; % note: not in ascending order
d = (A(:)'-B(:));
d(d>=0)= -inf;
[~, idx] = max(d,[],1)
idx = 1×6
1 3 3 2 4 2
Both solutions assume that at least 1 value in B is less than A(i). If this is not the case, you append inf to the end of B and if idx contains the index equal to the location of the final inf, you can replace it with 0. For example,
A = [99 ;7.5;9;10.5;15;14]; % Note; starts with 90
B = 5:5:50;
[~, idx] = max(A(:)'<[B(:);inf],[],1);
idx(idx==numel(B)+1) = 0
idx = 1×6
0 2 2 3 4 3