How can I merge multiple columns between two matrices?

1 回表示 (過去 30 日間)
Joseph Gaglione
Joseph Gaglione 2020 年 9 月 3 日
編集済み: Bruno Luong 2020 年 9 月 3 日
I'm looking for a better way to merge two matrices based on a third. To take the first column one matrix and the second, third etc from the second based on custom mapping. For example:
a =
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
b =
4 5 6 7
4 5 6 7
4 5 6 7
4 5 6 7
c =
0 1 1 0
Using c to combine a and b I would want to get a final matrix d which looks like:
d =
1 5 6 4
1 5 6 4
1 5 6 4
1 5 6 4
Currently I'm using a loop to select colums one at a time based on the c value, but this can get a little slow for larger matrices. Is there a simpler way to combine two matrices in this way?
Thanks

採用された回答

madhan ravi
madhan ravi 2020 年 9 月 3 日
In one line:
d = (~c .* a) + (c .* b)

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 9 月 3 日
編集済み: Bruno Luong 2020 年 9 月 3 日
d = a
d(:,c==1) = b(:,c==1)
  1 件のコメント
Bruno Luong
Bruno Luong 2020 年 9 月 3 日
編集済み: Bruno Luong 2020 年 9 月 3 日
NOTE: This method works even if a or b contains -Inf/+Inf and NaN

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by