question about indexing of logic matrix

2 次查看(过去 30 天)
Hi:
I read through the blog presented in link:
there is an operation using command:
mask(hel.faces)
Where hel.faces is a m*3 matrix, and mask is a n*1 logic matrix. I could not understand how could this operation happens because it can not reproduce in my side. my test commands are:
A=rand(20,3);
B=rand(20,1);
C=B>0.5;
C(A)
could anyone give me some suggestions?
Thanks!
Yu

采纳的回答

Stephen23
Stephen23 2019-10-2
编辑:Stephen23 2019-10-2
Your mistake is on this line:
A=rand(20,3);
You correctly wrote that "hel.faces is a m*3 matrix", but you seem to have missed that its values are all indices, i.e. positive integers, with values from 1 to numel(mask):
>> numel(mask)
ans =
121368
>> max(hel.faces(:))
ans =
121368
>> min(hel.faces(:))
ans =
1
>> find(mod(hel.faces(:),1)) % only integers
ans =
Empty matrix: 0-by-1
That is why it can be used as an index into another array (e.g. mask): because it it contains indices.
But you generated A with random numbers between 0 and 1, which are not indices (indices must be positive integers). Once you generate A with positive integers, with values from 1 to numel(B), then your code will work:
>> B = rand(20,1);
>> A = randi([1,20],20,3);
>> C = B>0.5;
>> C(A)
ans =
0 1 0
1 1 0
0 0 0
1 0 0
0 1 1
0 1 1
1 1 0
1 1 0
0 1 0
1 0 0
1 0 0
1 0 0
0 0 0
1 1 1
1 0 1
0 1 0
0 1 1
0 0 0
1 1 1
1 1 1
  3 个评论
Adam Danz
Adam Danz 2019-10-2
编辑:Adam Danz 2019-10-2
My answer moved here as a supplement to Stephen's answer.
" Where hel.faces is a m*3 matrix, and mask is a n*1 logic matrix. I could not understand how could this operation happens"
In that blog article, mask is a [121368 x 1] logical vector and hel.faces is a [239778, 3] matrix of integers. Note that the range of values in hel.faces is
min(hel.faces(:)) % = 1
max(hel.faces(:)) % = 121368 = numel(mask)
These values are linear indices of the mask vector. Here's a demo with a smaller amount of data to illustrate this point:
a = -3:6;
b = [4 7 7
5 6 3
6 3 1];
a(b)
ans =
0 3 3 % a(4) a(7) a(7)
1 2 -1 % a(5) a(6) a(3)
2 -1 -3 % a(6) a(3) a(1)

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2019-10-2
This is linear indexing into a logical array.
A = [true false]
B = randi(2, 5, 5)
C = A(B)
The elements of C that are true (A(1)) correspond to elements in B that are 1.
The elements of C that are false (A(2)) correspond to elements in B that are 2.
Perhaps a different example, one that has a few more unique values from which to select, would illustrate the technique more clearly.
D = ["Ace of spades"; "Queen of hearts"; "7 of diamonds"; "Jack of clubs"]
selection = randi(numel(D), [4 4])
selectedCards = D(selection)
Element 11 of selectedCards is the element in D whose index is stored in element 11 of selection.

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by