Clear Filters
Clear Filters

create a zero-one matrix from non zero matrix ?

3 views (last 30 days)
AZAB
AZAB on 28 Feb 2020
Edited: AZAB on 28 Feb 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?

Answers (1)

Temu
Temu on 28 Feb 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 Comments
Temu
Temu on 28 Feb 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 on 28 Feb 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!

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!