How to find the index of vector that corresponds w

2019-07-22 14:01发布

问题:

I have a vector such as

A=[0.2 0.5 0.4 0.6] 

that labels as the

A_labels=[1 2 3 4]

and other vector B equals

B=[30 10 20]

I assume that the highest values of vector B will be assigned for highest label in A, and reduces by order. That means

30 will assign for 4
10 will assign for 2
20 will assign for 3

I will scan all element of vector B and I want to find which labels corresponding with its based on above rule. Could you help me implement that scheme in MATLAB? Thanks

A=[0.2 0.5 0.4 0.6]
A_lables=1:1:size(A,2);
B=[30 10 20];
for i=1:size(B,2)
    //Find label of A_labels corresponds with B(i)
    // Result will be [4 2 3]
end

回答1:

I think this does what you want. I'm assuming A_labels is sorted, as in your example.

[~, ind] = sort(B); %// sort B and get *indices* of the sorting
[~, ind] = sort(ind); %// get *rank* of each element of B
result = A_labels(end-numel(ind)+ind);


回答2:

Not sure I've fully understood but can't you just sort B and A_labels descending and use the sort order from B as an index on the ordered A_labels?

So

[~,idx] = sort(B,'descend');
A_labels_ordered = sort(A_labels, 'descend');

result = A_labels_ordered(idx)


标签: matlab vector