Index Matrix A and Matrix B Problems

1 Ansicht (letzte 30 Tage)
jane
jane am 24 Jun. 2022
Bearbeitet: Dhritishman am 3 Jul. 2022
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

Antworten (3)

James Tursa
James Tursa am 24 Jun. 2022
Bearbeitet: James Tursa am 24 Jun. 2022
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 Kommentare
James Tursa
James Tursa am 24 Jun. 2022
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 am 24 Jun. 2022
Thanks James

Melden Sie sich an, um zu kommentieren.


Voss
Voss am 24 Jun. 2022
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 Kommentare
jane
jane am 24 Jun. 2022
Thank You
Voss
Voss am 24 Jun. 2022
You're welcome!

Melden Sie sich an, um zu kommentieren.


Dhritishman
Dhritishman am 3 Jul. 2022
Bearbeitet: Dhritishman am 3 Jul. 2022
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

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by