Effacer les filtres
Effacer les filtres

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

4 vues (au cours des 30 derniers jours)
Bruce MacWilliams
Bruce MacWilliams le 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.

Réponses (1)

Bruce MacWilliams
Bruce MacWilliams le 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
  1 commentaire
Michael Schwartz
Michael Schwartz le 31 Mai 2019
This seems like a very clever and efficient solution!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by