Index Matrix A and Matrix B Problems

1 visualizzazione (ultimi 30 giorni)
jane
jane il 24 Giu 2022
Modificato: Dhritishman il 3 Lug 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

Risposte (3)

James Tursa
James Tursa il 24 Giu 2022
Modificato: James Tursa il 24 Giu 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 Commenti
James Tursa
James Tursa il 24 Giu 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 il 24 Giu 2022
Thanks James

Accedi per commentare.


Voss
Voss il 24 Giu 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 Commenti
Voss
Voss il 24 Giu 2022
You're welcome!

Accedi per commentare.


Dhritishman
Dhritishman il 3 Lug 2022
Modificato: Dhritishman il 3 Lug 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

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by