Search code examples
arraysmatlabdata-mapping

Matlab grouping Data into Triples from a 2d Array


Is there a smart way grab Values from a 2d Array in Pairs and additionally to that the last number in the row?

My Data (saved in a file) look something similar to this:

  0  89  27 100  42  75 8  
  0 100   7  92   5  68 6  
  0  67  49  83 100 100 2  
 35  76  57 100 100  92 5  
 18  68  50  54 100  19 3  

After loading this Data into Matlab I need to group up the Data into Tuples by always taking the Pairs. In this Example it would be:

[0,89],[27,100],[42,75],[0,100],...[100,19]

After the pairing the Data (or meanwhile), I need to add the last Number in the row to the Pairs. The Previous mentioned Data would be altered followingly:

[0,89,8],[27,100,8],[42,75,8],[0,100,6],...[100,19,3]

How would be a smart way to solve this? I personally dislike the extensive use of Loops and think there is a nicer Solution.


Solution

  • Edit: This should do the trick.

    M=[0  89  27 100  42  75 8  
      0 100   7  92   5  68 6  
      0  67  49  83 100 100 2  
     35  76  57 100 100  92 5  
     18  68  50  54 100  19 3]
    
    X = M(:,1:end-1)
    Y = M(:,end)
    idxOdd = mod(1:size(X,2),2)==1
    Xeven=X(:,~idxOdd)
    Xodd=X(:,idxOdd)
    
    Yrep = repmat(Y,1,sum(idxOdd))
    
    [Xodd(:) Xeven(:) Yrep(:)]