create a zero-one matrix from non zero matrix ?

1 次查看(过去 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?

回答(1 个)

Temu
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
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
AZAB
AZAB 2020-2-28
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!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by