user2100039
user2100039

Reputation: 1366

Create Index MATLAB

I'm fried from trying do this successfully. I have data A in a matrix with size(A) = [100 612]. The column data is in chunks of 12 months by 51 sites, i.e, 612 total columns.

I need to create an index to select columns in this sequence; 1:51:612 and then 2:51:612, etc. up to 51:51:612. The final array should be a 100 row by 612 column matrix with this sequence

Row 1: Columns 1-12=(1,52,103,154,205,256,307,358,409,460,511,562)
       Columns 13-24=(2,53,104,155,206,257,308,359,410,461,512,563)
       ...
       etc to the end of the first row with the last 12 columns with these numbers 
       Columns 601-612=(51,102,153,204,255,306,357,408,459,510,561,612).

Then repeated 100 times to give 100 rows. I need this to use as a logical index for extracting or to re-sort the original data in A given above.

Upvotes: 1

Views: 104

Answers (2)

Santhan Salai
Santhan Salai

Reputation: 3898

Here is a one-liner using permute and reshape

out = A(:,reshape(permute(reshape(1:612,51,[]),[2 1 3]),1,[]));

Or you could just avoid permute by using transpose

out = A(:,reshape(reshape(1:612,51,[]).',1,[]));

Upvotes: 4

eigenchris
eigenchris

Reputation: 5821

The following code should work:

months = 12;
sites = 51;

idx       = 1:sites:months*sites;           %// get array [1,52,103,...,562]
final_idx = bsxfun(@plus,idx',[0:sites-1]); %'//add offsets to idx  
final_idx = final_idx(:)';                  %'//get array elements in a row vector

A_new = A(:,final_idx);                     %// rearrange columns 

Upvotes: 2

Related Questions