How to get two matrices with different element values from a mother matrix?

5 vues (au cours des 30 derniers jours)
I have this matrix:
A=[2 0 1; 1 2 1; 2 2 1]; %main matrix
I want a code that can extract two matrices, one with 1's elements and anything else is zero and the second matrix with 2's elements and anything else is zero. So, I want to get them as following:
a1=[0 0 1; 1 0 1; 0 0 1] % sub matrix with 1's elements only
a2=[2 0 0; 0 2 0; 2 2 0] % sub matrix with 2's elements only
Can anyone helps?

Réponse acceptée

Guillaume
Guillaume le 7 Juin 2017
a1 = zeros(size(A));
a1(A == 1) = A(A == 1);
Do the same for a2 obviously replacing the A == 1 by A == 2.
  2 commentaires
AbuYusuf
AbuYusuf le 7 Juin 2017
Perfect! thanks so much
Guillaume
Guillaume le 7 Juin 2017
Modifié(e) : Guillaume le 7 Juin 2017
Just realised that it could be even simpler:
a1 = zeros(size(A));
a1(A == 1) = 1; %a2(A == 2) = 2;

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by