What does L == 2 mean in MATLAB?
BW = logical([1 1 1 0 0 0 0 0
1 1 1 0 1 1 0 0
1 1 1 0 1 1 0 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 1 1 0
1 1 1 0 0 0 0 0]);
L = bwlabel(BW,4);
[r,c] = find(L == 2);
How can开发者_Go百科 a matrix been compared with scalar?
Maybe a visual example might help.
>> b=[1 2 3;2 3 1;3 1 2]
b =
1 2 3
2 3 1
3 1 2
>> b==2
ans =
0 1 0
1 0 0
0 0 1
>> b==3
ans =
0 0 1
0 1 0
1 0 0
A logical-class matrix of the same size as the matrix being compared is returned.
>> find(ans)
ans =
2
4
9
find
then returns the linear address of the non-zero elements.
Afair comparing a matrix with an scalar results in element-wise comparison. I.e. each element of the matrix is compared with the scalar. The result is a matrix with 1 in all positions for which the comparison returned true and 0 in all other positions.
find
on the other hand returns all indices for which the argument is non-zero.
"How can a matrix been compared with scalar?": try doc eq
at the matlab prompt and it says:
A == B compares each element ... for equality ... Each input of the expression can be an array or a scalar value.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it were an array having the same dimensions as the nonscalar input array. In other words, if input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5 matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as the nonscalar input array.
The find(L==2)
will return all the rows and columns of elements that are equal to 2.
So, if you get [r]=[1 2 3 5 6]
and [c]=[1 2 3 5 6]
, that means that the rows and columns of the elements that are equal to 2 is {1,1}
, {2,2}
, {3,3}
and so on.
The official matlab explanation is here. You can also google the term "matlab find"
See the bwlabel
function, it will be useful for you.
Example:
Label components using 4-connected objects. Notice objects 2 and 3; with 8-connected labeling, bwlabel
would consider these a single object rather than two separate objects.
BW = logical ([1 1 1 0 0 0 0 0
1 1 1 0 1 1 0 0
1 1 1 0 1 1 0 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 1 1 0
1 1 1 0 0 0 0 0]);
L = bwlabel(BW,4)
L =
1 1 1 0 0 0 0 0
1 1 1 0 2 2 0 0
1 1 1 0 2 2 0 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 3 3 0
1 1 1 0 0 0 0 0
[r, c] = find(L==2);
rc = [r c]
rc =
2 5
3 5
2 6
3 6
Another explanation:
Say,
A = [1 2 3
4 5 6
7 8 9]
then when you say:
A == 5;
what MATLAB sees (the actual implementation is for more different than this, but the logic stays the same):
A == B*5;
where,
B = [1 1 1
1 1 1
1 1 1];
You can extend this for an arbitrary A matrix.
Same for addition.
精彩评论