statistic
statistic

Reputation: 181

Matlab Array Sorting

I have an array(from excel file) like this;

raw =

':Gamer Name'    'mail'                    'true'    'false'    'Date'               
'Haydar'         [                   1]    [2]    [3]    [                   5]
'Çınar'         [                   3]    [4]    [1]    [                   6]
'Ali'            [                   2]    [5]    [2]    [                   3]
' Oyuncu'        [                 NaN]    [0]    [3]    [                 NaN]
' Oyuncu'        [                 NaN]    [0]    [3]    [                 NaN]
' Oyuncu'        [                 NaN]    [0]    [3]    '11-Apr-2017 19:17:10'
' Haydar'        'haydarc'                 [0]    [3]    '11-Apr-2017 19:22:14'
[        NaN]    [                 NaN]    [0]    [3]    '11-Apr-2017 19:24:40'
[        NaN]    [                 NaN]    [3]    [0]    '11-Apr-2017 19:27:45'
' Haydar'        'haydarcinar@yandex…'    [3]    [0]    '11-Apr-2017 20:02:04'

I want to sort by 'True'. How can i do this ? Thanks

Upvotes: 1

Views: 56

Answers (1)

rayryeng
rayryeng

Reputation: 104555

You can extract out the indices of sorting through sort based on the third column (i.e. true) of your cell array, then rearrange the rows of your cell array based on that. Use the second output of sort to help you do this.

However, your first row consists of characters. What you'll need to do is pull out the first row, sort on the numerics, then reconstruct the sorted cell array putting this first row back:

raws = raw(2:end, :);
[~,ind] = sort(cell2mat(raws(:, 3));
raw_sorted = [raw(1,:); raws(ind, :));

The function cell2mat helps convert your column of cells in the true column to be a matrix so we can successfully use sort. Once we find the indices of sorting, simply index into your cell array without the first row, but make sure you place the first row back.

Upvotes: 4

Related Questions