Find 2nd minimum value from a row after addition

1 view (last 30 days)
[c,ix] = min(sum(A,2));
This code will give the minimum value from a row after addition, https://www.mathworks.com/matlabcentral/answers/82429-minimum-row-value-and-return-the-row
Similar to this, how to find the 2nd minimum value from the same row?
Can someone help me out?

Accepted Answer

KSSV
KSSV on 17 May 2017
Edited: KSSV on 17 May 2017
You can sort your row and pick what ever minimum you want.
A = rand(10) ;
% [c,ix] = min(sum(A,2));
[val,idx] = sort(sum(A,2)) ;
min1 = val(1)
min2 = val(2)
min3 = val(3)
  7 Comments
Stephen23
Stephen23 on 17 May 2017
Edited: Stephen23 on 17 May 2017
@Asim Ismail: What KSSV gave you is not a general solution to the task. It works by replacing one element with NaN, and then traversing the elements again. As you can see by my tests of KSSV's FEX submission that uses this concept, it is extremely inefficient when used as a general solution:
n = 1e5;
vec = randi(1e4,1,1e6);
takes this long to run once:
Elapsed time is 0.068590 seconds. % using sort
Elapsed time is 1036.380380 seconds. % KSSV's code (sixteen minutes)
While it does work, this algorithm is extremely slow when used to find any arbitrary element. Sorting with sort is usually going to be the best solution (fastest, simplest, neatest, most efficient, easiest to understand the purpose,...). The sort algorithm that KSSV used is a version of a "selection sort", which are described on wikipedia as "...inefficient on large lists".
Asim Ismail
Asim Ismail on 17 May 2017
@Stephen Cobeldick, thanks for information, I will take it consideration, and you are right @KSSV's method is not a general solution.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!