简体   繁体   中英

Find the index of the previous row in a table in Matlab

If I have the following table in Matlab:

T = table(['KAT';'MAT';'PAT';'SAT';'RAT'],[38;43;38;40;49],[71;69;64;67;64],[176;163;131;133;119])


T =

  5×4 table

    Var1    Var2    Var3    Var4
    ____    ____    ____    ____

    KAT      38      71     176 
    MAT      43      69     163 
    PAT      38      64     131 
    SAT      40      67     133 
    RAT      49      64     119

How do i refer to the entire row above PAT.

For example, the below code finds the row matching to PAT

>> T((ismember(T.Var1,'PAT','rows')),:)

ans =

  1×4 table

    Var1    Var2    Var3    Var4
    ____    ____    ____    ____

    PAT      38      64     131 

But when I deduct 1 in the index to find the row above the matched row for 'PAT' , i get the following error :

>> T((ismember(T.Var1,'PAT','rows')-1),:)
Index in position 1 is invalid. Array
indices must be positive integers or logical
values.

Is there any way i could find the row above to the row that matched for 'PAT' ??

The output from your ismember is a vector [0 0 1 0 0]' . If you subtract one from that you get [-1 -1 0 -1 -1]' which isn't a valid index. A simple solution is to use find and then subtract 1.

T((find(ismember(T.Var1, 'PAT', 'rows'))-1), :)

ans = 

    Var1    Var2    Var3    Var4

    ____    ____    ____    ____

    MAT     43      69      163 

find returns the indices of non-zero elements.

Another option is to use circshift to move elements in the vector.

T(circshift(ismember(T.Var1, 'PAT', 'rows'),-1), :)

ans = 

    Var1    Var2    Var3    Var4
    ____    ____    ____    ____

    MAT     43      69      163 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM