× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How can I find the indices of the 2 smallest elements in a vector without sorting?

Ray Phan
Jan 30, 2015
<p>Phil Goddard's answer is perfectly acceptable. However, you did say that you want to do this without sorting, so I'm assuming you don't want to use the <code>sort</code> function at all. What you can do is use <code>min</code> twice. Once you invoke it the first time and you find the index of the minimum element, you would set this location in your array to <code>NaN</code>, then run <code>min</code> an additional time. By setting the location to <code>NaN</code>, you would effectively skip the element that is equal to the smallest at that point in time. After you call <code>min</code> the second time, you'll get the second smallest element. </p> <p>One small thing you'll need to do afterwards is to clear off the <code>NaN</code> you set in the array after the first <code>min</code> call. You do this by extracting what the minimum value was after the first call, in addition to where this minimum value was located. Once you call <code>min</code> a second time, you'd reset the location of where the first minimum was from <code>NaN</code> back to its original value. </p> <p>In other words:</p> <pre><code>a = [1,5,8,7,1]; [min1,ind1] = min(a); a(ind1) = NaN; [~,ind2] = min(a); a(ind1) = min1; %// Copy back to ensure we get original data back </code></pre> <p><code>ind1</code> and <code>ind2</code> will contain the locations of the two smallest values in <code>a</code>. With your example, I get:</p> <pre><code>disp([ind1 ind2]) 1 5 </code></pre> <p>Similarly, for <code>b</code>, this is what we get with the above code:</p> <pre><code>disp([ind1 ind2]) 1 4 </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25882114/How%20can%20I%20find%20the%20indices%20of%20the%202%20smallest%20elements%20in%20a%20vector%20without%20sorting?/25882521">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus