Borrar filtros
Borrar filtros

create a zero-one matrix from non zero matrix ?

1 visualización (últimos 30 días)
AZAB
AZAB el 28 de Feb. de 2020
Editada: AZAB el 28 de Feb. de 2020
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?

Respuestas (1)

Temu
Temu el 28 de Feb. de 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 comentarios
Temu
Temu el 28 de Feb. de 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
AZAB
AZAB el 28 de Feb. de 2020
Got it , Thank you it is working !
Now, I am tryign a larger scale
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
in this case how to define B ?
thanks in advance!

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by