bnbfreak
bnbfreak

Reputation: 353

Sorting multi rows from a file using Matlab

I have a file with various total number of columns as below :

1.000000 - 1.000200 0 -> 2 A-MPDU 1.000000 - 1.000100 SUCCESS 1.000100 - 1.000200 FAIL
1.000225 - 1.000270 2 -> 0 ACK SUCCESS [01]
1.000150 - 1.000350 1 -> 3 A-MPDU 1.000150 - 1.000250 FAIL 1.000250 - 1.000350 FAIL
1.000425 1 TIMEOUT
1.000270 - 1.000570 0 BACKOFF

I want to sort these rows based on columns4 for row1, 2, 3, 5 and column2 for row4 (in other words, based on column2 or column4) thus it should be like this after sorting :

1.000000 - 1.000200 0 -> 2 A-MPDU 1.000000 - 1.000100 SUCCESS 1.000100 - 1.000200 FAIL
1.000270 - 1.000570 0 BACKOFF
1.000150 - 1.000350 1 -> 3 A-MPDU 1.000150 - 1.000250 FAIL 1.000250 - 1.000350 FAIL
1.000425 1 TIMEOUT
1.000225 - 1.000270 2 -> 0 ACK SUCCESS [01]

How to realize this output? Should I count total number of column for each row first to decide whether I use column2 or column4?

Upvotes: 0

Views: 47

Answers (1)

Dev-iL
Dev-iL

Reputation: 24159

Looks like your data has a well-known structure. The easiest to understand (but not necessarily cleanest) thing I could think of is as follows:

  1. Read the text as one long string:

    A = [... '1.000000 - 1.000200 0 -> 2 A-MPDU 1.000000 - 1.000100 SUCCESS 1.000100 - 1.000200 FAIL'... char (10) '1.000225 - 1.000270 2 -> 0 ACK SUCCESS [01]'... char (10) '1.000150 - 1.000350 1 -> 3 A-MPDU 1.000150 - 1.000250 FAIL 1.000250 - 1.000350 FAIL'... char (10) '1.000425 1 TIMEOUT'... char (10) '1.000270 - 1.000570 0 BACKOFF'... ];

    Note: char(10) is a line break \n. You should get this automatically if reading from a text file.

  2. Split the long string into separate cells by using: B=(strsplit(A,char(10)))';

  3. Use C = cellfun(@strsplit,B,repmat({' '},size(B)),'UniformOutput',0); to convert it into a cell array (some rows will contain empty cells at the end because the initial string has less spaces).

  4. Convert the 1D array of 1D cell arrays into a single 2D array by: D=C; for ind1=1:length(D) tmp = length(D{ind1}); D(ind1,1:tmp)=D{ind1}; end

  5. Find the rows where the result has a number in the 2nd column:

    isInd = ~strcmp('-',D(:,2))

  6. Create a list of indices by: idx(ind1,1)=0; %Preallocation for ind1=1:ind1 %Extreme variable reuse idx(ind1) = str2double(D(ind1,4-2*isInd(ind1))); end

  7. Append indices to the array you want to sort and sort according to them: B1 = sortrows([B,num2cell(idx)],2); B_Sorted = B1(:,1);

The result, with this code, is a sorted cell array.


P.S. Anybody who is willing to optimize this code is more than welcome to edit the answer :)

Upvotes: 1

Related Questions