create a zero-one matrix from non zero matrix ?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
if I have a matrix A=[a b;c d] i want to convert to a matrix of zeros and ones based on the value and position of the elements in this matrix ,
if element "a" is nonzero and exists as the first element (1st row and 1st column) in matrix A then "a" to be represented in an array such that a --> [ 1 0 0 0 ] ,
b --> [ 0 1 0 0] , c --> to be [0 0 1 0] , and d --> [ 0 0 01]
so i want to make such conversion
A = [ a b
c d]
B = [ 1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1]
first array to represent element "a" is to tell that element "a" is non zero so that it have value of 1 and it is in (1 st raw, 1st column and not exists in any other location in the matrix A)
if A =[3 0
5 7]
then B=[ [1 0], [0 0] -->3
[0 0 ],[1 0] -->5
[0 0],[ 0 1] ] --> 7
and if A=[1 2 3
4 4 0
6 8 7]
to get B=[ [1 0 0 , 0 0 0, 0 0 0 ] -->1
[0 1 0 , 0 0 0 , 0 0 0 ] --> 2
[0 0 1 , 0 0 0, 0 0 0 ] -->3
[0 0 0 , 1 0 0, 0 0 0 ] -->4
[0 0 0 , 0 1 0, 0 0 0 ] -->4
[0 0 0 , 0 0 0, 1 0 0 ] -->6
[0 0 0 , 0 0 0, 0 1 0 ] -->8
[0 0 0 , 0 0 0, 0 0 1 ] ] -->7
How to do this , please?
0 commentaires
Réponses (1)
Temu
le 28 Fév 2020
Hi,
I tried to get this into a one-liner, but couldn't. I got close, though:
possibleChars = 'abcd';
A = 'ab0d';
B = bsxfun( @( x2, y2 ) bsxfun( @(x1,y1)(x1==y1), possibleChars, x2 ), A', 1 );
B(sum(B,2)==0,:) = [];
hth,
Temu
3 commentaires
Temu
le 28 Fév 2020
Just substitute the strings with numbers:
possibleChars = [2 4 5];
A = [2 4 5 0];
B = bsxfun( @( x2, y2 ) bsxfun( @(x1,y1)(x1==y1), possibleChars, x2 ), A', 1 );
B(sum(B,2)==0,:) = []
Temu
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!