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

5 次查看(过去 30 天)
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