- #1
mikeph
- 1,235
- 18
I have a 100x1 vector A, and want to know the ten indices i for which A(i) are the greatest 10 values in A.
I can find the values by:
But I don't know how to find the indices, apart from starting a new if loop which searches the entire matrix (which seems very time consuming).
As another example, I have a matrix B which is 10,000x2 and I want to know the value of B(i,1) for which B(i,2) is the maximum value in the column vector B(:,2). Eg.
However I think this is taking absolutely ages in my code (I need to find this 20bn times so it's definitely an area for optimisation). Is there a simpler way to find the indices?
I can find the values by:
Code:
B = sort(A)
B(1:10);
But I don't know how to find the indices, apart from starting a new if loop which searches the entire matrix (which seems very time consuming).
As another example, I have a matrix B which is 10,000x2 and I want to know the value of B(i,1) for which B(i,2) is the maximum value in the column vector B(:,2). Eg.
Code:
>> B = [(5:0.1:5.9)',rand(10,1)]
B =
5.000000000000000 0.696266337082995
5.100000000000000 0.093820026774866
5.200000000000000 0.525404403859336
5.300000000000000 0.530344218392863
5.400000000000000 0.861139811393332
5.500000000000000 0.484853333552102
5.600000000000001 0.393456361215266
5.700000000000000 0.671431139674026
5.800000000000001 0.741257943454206
5.900000000000000 0.520052467390387
>> for i = 1:10
if B(i,2) == max(B(:,2))
B(i,1)
end
end
ans =
5.400000000000000
However I think this is taking absolutely ages in my code (I need to find this 20bn times so it's definitely an area for optimisation). Is there a simpler way to find the indices?