Search code examples
loopsmatlabtextiteration

Flip rows with loop over large files in MATLAB


I have a huge ascii.txt wind file with the following format.

time = 0 hour
2 3 4 5 6 7 
0 9 8 7 6 5
7 6 5 4 3 2
9 8 7 6 5 4
time = 3 hour
2 3 4 5 6 7 
0 9 8 7 6 5
7 6 5 4 3 2
9 8 7 6 5 4

The thing is that I need to flip the rows from each block between hours, like this

time = 0 hour
9 8 7 6 5 4 
7 6 5 4 3 2
0 9 8 7 6 5
2 3 4 5 6 7 
time = 3 hour
9 8 7 6 5 4 
7 6 5 4 3 2
0 9 8 7 6 5
2 3 4 5 6 7 

I can do this for one block in MATLAB by

    X = readlines('xwind.txt');
    Y = X(2:5);
    Y = flip(Y);

But I couldn’t write the loop for the entire file (4865x1 string). Any help would be much appreciated.


Solution

  • You are trying to go between these two row orderings:

    OriginalRow: [1  2  3  4  5  6  7  8  9 10 ...]
    NewRow:      [1  5  4  3  2  6 10  9  8  7  ...]
    

    There is a repetitive pattern here in terms of the relative offset:

    RowOffset:   [0 +3 +1 -1 -3 0 +3 +1 -1 -3 ...]
    

    So a solution to shuffle by this many places could be

    N = numel(X);                              % Number of rows of text
    offst = repmat( [0 +3 +1 -1 -3], 1, N/5 ); % Repeat offset to same size as X
    Y = X( (1:N) + offst );                    % Create Y from reordered rows of X