Combine two (or multiple) columns into single vector by criteria

조회 수: 5 (최근 30일)
Bruce MacWilliams
Bruce MacWilliams 2019년 5월 31일
댓글: Michael Schwartz 2019년 5월 31일
Should be simple, but I'm not getting this. I have Left and Right data columns that I want to extract into a single vector based on a third "Side" column that specifies which side to use for each row, so for matrix/table A:
Side Left Right
L 1 2
R 3 4
R 5 6
L 7 8
Based on this I want to extract [1 4 6 7]
Easy enough to create Left and Right vectors that indicate which elements to use for each column:
LData = A.Side == 'L' %returns [1 0 0 1]
RData = A.Side == 'R' %returns [0 1 1 0]
But what is the next step to combine A.Left and A.Right to get [1 4 6 7]? I tried
Data = A.Left(LData) & A.Right(RData)
But this generates an error that "dimensions must agree". Of course I could use logic within a loop and do this row by row, but I'm sure there is an easier approach. Also, just for clarity, vertical concatenation where all Lefts are followed by all Rights are not what I'm aiming for.

답변 (1개)

Bruce MacWilliams
Bruce MacWilliams 2019년 5월 31일
I seem to have figured out at least one solution, using the index arrays (LData, RData) to multiply, so the solution using above would be:
Data = A.Left.*LData + A.Right.*RData

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by