Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
Bruce MacWilliams
Bruce MacWilliams am 31 Mai 2019
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.

Antworten (1)

Bruce MacWilliams
Bruce MacWilliams am 31 Mai 2019
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

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by