question about indexing of logic matrix

1 view (last 30 days)
Yu Li
Yu Li on 2 Oct 2019
Commented: Yu Li on 2 Oct 2019
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

Accepted Answer

Stephen23
Stephen23 on 2 Oct 2019
Edited: Stephen23 on 2 Oct 2019
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 Comments
Yu Li
Yu Li on 2 Oct 2019
thank you all very much!
Bests,
Yu

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 2 Oct 2019
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.
  1 Comment
Yu Li
Yu Li on 2 Oct 2019
Hi Steven:
thank you all the same!
Bests,
Yu

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!