How to get the index from a matrix?
3 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Adam Danz
on 17 Nov 2020
Edited: Adam Danz
on 17 Nov 2020
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)
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)
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
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!