problem with vector logic

조회 수: 1 (최근 30일)
Christopher
Christopher 2014년 10월 2일
답변: Star Strider 2014년 10월 2일
Why doesn't the final logical operation work?
Oneigh=zeros(10,10);
r = round(0.5+rand(10,10)*8);
Oneigh(r==1)=r;
For the elements where r==1, Oneigh should adopt the corresponding value in r.
By the way for the operation:
Oneigh(r==1)=r;
should actually be
Oneigh(r==1)=O1;
where O1 is another matrix of the same size, but the above is simpler and not working.

답변 (2개)

Geoff Hayes
Geoff Hayes 2014년 10월 2일
Christopher - if you run the following code, the line
Oneigh(r==1)=r;
is probably generating the
In an assignment A(I) = B, the number of elements in B and I must be the same.
error message. Look closely at what is happening
>> r==1
ans =
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0
is a 10x10 matrix. Now look at
>> Oneigh(r==1)
ans =
0
0
0
0
0
0
0
0
0
is a 9x1 vector corresponding to the elements of Oneigh indexed on the logical matrix generated by r==1. So
Oneigh(r==1)=r;
tries to assign a 10x10 matrix (r) to the 9x1 column vector, and the error makes sense.
As you say, for the elements where r==1, Oneigh should adopt the corresponding value in r, then this could be simplified to
Oneigh(r==1)=1;
since the corresponding value in r is 1.
Else, if you know the indices in r that are identical to 1, then we can use that information to update Oneigh given O1 as
idcs = find(r==1);
Oneigh(idcs) = O1(idcs);

Star Strider
Star Strider 2014년 10월 2일
If you want ‘Oneigh’ to be a matrix with only any particular value of ‘r’ existing and with zeros elsewhere, It’s a bit more involved but still relatively straightforward:
Oneigh=zeros(10,10);
r = round(0.5+rand(10,10)*8);
iv = 1; % Integer To Match
q = r==iv; % Logical Array
Oneigh = r; % Assign ‘Oneigh’ As ‘r’
Oneigh(~q) = 0; % ‘Oneigh’ Now Has ‘iv’ Matching ‘r’, Zero Elsewhere
Note that in this method there is actually no need to preallocate ‘Oneigh’. I retained it for consistency. You can also use the randi function to generate ‘r’.

카테고리

Help CenterFile Exchange에서 Get Started with Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by