Search code examples
octaveoctave-gui

Trying to find index of minimum value in a list of vars in Octave


I have a list of vars with different values

a = 2
b = 1
c= 12343243
d = 8998

Can find the smallest value

aSmallestVALUE = min([a, b, c, d])

and index

[v,idx]=min([a, b, c, d])

I want to find the index of variable and sort this list from 0 to up something like the

sorted list = b, a, d, c

Solution

  • Obviously if you want to treat those four variables as a 'list' to be sorted, you need to be working with a 'list' construct, not 4 isolated variables.

    L = [2, 1, 12343243, 8998];
    

    Otherwise it makes no sense to talk about the 'index' of an existing independent variable (though obviously you can construct this L from a bunch of pre-existing variables if desired).

    With L in hand, you can now do

    [minval, idx] = min( L )
    % minval = 1
    % idx = 2
    

    to find the minimum and its corresponding index, and

    [sorted, sortedindices] = sort( L )
    % sorted =
    %    1.0000e+00   2.0000e+00   8.9980e+03   1.2343e+07
    %
    % sortedindices =
    %    2   1   4   3
    

    to obtain a sorted array, with corresponding indices.