create a zero-one matrix from non zero matrix ?
    조회 수: 4 (최근 30일)
  
       이전 댓글 표시
    
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
답변 (1개)
  Temu
 2020년 2월 28일
        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
  Temu
 2020년 2월 28일
				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
참고 항목
카테고리
				Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

