Index Matrix A and Matrix B Problems

1 回表示 (過去 30 日間)
jane
jane 2022 年 6 月 24 日
編集済み: Dhritishman 2022 年 7 月 3 日
i have matrix A and Matrix B
A = [[ 0, 1, 1, 0, 1, 0,1],
[ 0, 0, 1, 1, 0, 0,0],
[ 1, 1, 0, 1, 1, 0,0]],
B = [[ 234, 59, 15, 99, 61, 74 ,71],
[ 16, 27, 14, 13, 111, 345.67],
[ 54, 23, 16, 14, 13, 27,100]],
How to make the value in matrix B be 0 if the value in matrix A is 1.
For example, in matrix A (row 1, column 2), the value of 1 in matrix B (row 1, column 2) will be 0.
I tried using loop but it didn't work. Thank you

回答 (3 件)

James Tursa
James Tursa 2022 年 6 月 24 日
編集済み: James Tursa 2022 年 6 月 24 日
You can use logical indexing:
B(A==1) = 0;
You can use a loop for this also, but you would have to show us the code you used before we can tell you what you did wrong with that approach.
  3 件のコメント
James Tursa
James Tursa 2022 年 6 月 24 日
If on the other hand you want the A==1 spots to contain original B values and the other spots to become zero, then simply change the comparison operator used from "equals" to "not equals":
B(A~=1) = 0;
jane
jane 2022 年 6 月 24 日
Thanks James

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


Voss
Voss 2022 年 6 月 24 日
A = [ 0, 1, 1, 0, 1, 0,1; 0, 0, 1, 1, 0, 0,0; 1, 1, 0, 1, 1, 0,0]
A = 3×7
0 1 1 0 1 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0
B = [ 234, 59, 15, 99, 61, 74 ,71; 16, 27, 14, 13, 111, 345,67; 54, 23, 16, 14, 13, 27,100]
B = 3×7
234 59 15 99 61 74 71 16 27 14 13 111 345 67 54 23 16 14 13 27 100
B(A == 1) = 0
B = 3×7
234 0 0 99 0 74 0 16 27 0 0 111 345 67 0 0 16 0 0 27 100
  4 件のコメント
jane
jane 2022 年 6 月 24 日
Thank You
Voss
Voss 2022 年 6 月 24 日
You're welcome!

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


Dhritishman
Dhritishman 2022 年 7 月 3 日
編集済み: Dhritishman 2022 年 7 月 3 日
MATLAB provides logical indexing which can be used to select or modify elements of a matrix.
A = [0, 1, 1, 0, 1, 0, 1; 0, 0, 1, 1, 0, 0,0; 1, 1, 0, 1, 1, 0,0]
A = 3×7
0 1 1 0 1 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0
B = [234, 59, 15, 99, 61, 74, 71; 16, 27, 14, 13, 111, 345, 67; 54, 23, 16, 14, 13, 27, 100]
B = 3×7
234 59 15 99 61 74 71 16 27 14 13 111 345 67 54 23 16 14 13 27 100
% This line of code changes the value in matrix B to 0 if the value of the corresponding element in matrix A is 1.
B(A == 1) = 0
B = 3×7
234 0 0 99 0 74 0 16 27 0 0 111 345 67 0 0 16 0 0 27 100

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by