Lets Learn together... Happy Reading

" Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference "-Robert Frost

Array sorting in MATLAB

                 Sorting an array and retrieving the minimum and maximum values with the index may seem simpler but this helped me in many ways especially when working with arrays. So this is just a refresh on how to sort a 1 and 2d arrays.

Single dimensional array sorting

To sort the array and display the position (index):

A = [5 8 9 10 100 7 50 8 88 6;];

Before sorting:
A =   5     8     9    10   100     7    50     8    88     6

[sorted_array,pos]= sort(A)

After sorting: Here the sorted array and the array position of each value will be displayed.
By default, sorting type is ‘ascending’.


sorted_array =     5     6     7     8     8     9    10    50    88   100


pos =     1    10     6     2     8     3     4     7     9     5


To find the maximum value:
A =   5     8     9    10   100     7    50     8    88     6

[max_value,max_pos]=max(A)

max_value  =    100


max_pos  =      5

To find the minimum value:

A =   5     8     9    10   100     7    50     8    88     6


[min_value,min_pos]=min(A)

min_value =      5


min_pos =      1


Two dimensional array sorting:

B=[17 5 8 9; 45 23 50 6; 7 49 21 11]


Before sorting:

B =     17     5     8     9
           45    23    50     6
            7    49    21    11


[sorted_array, pos]=sort(B(:))

After sorting:

sorted_array =

     5
     6
     7
     8
     9
    11
    17
    21
    23
    45
    49
    50


pos =

     4
    11
     3
     7
    10
    12
     1
     9
     5
     2
     6
     8

Maximum value:
[sorted_array, pos]=max(B(:))

sorted_array =

    50


pos =

     8


Minimum Value:
[sorted_array, pos]=min(B(:))

sorted_array =

     5


pos =

     4

To retrieve the minimum value: B(4)
ans =      5
like button Like "IMAGE PROCESSING" page

0 comments:

Enjoyed Reading? Share Your Views

Previous Post Next Post Home
Google ping Hypersmash.com