MATLAB Answers

Should this logical indexing throw an error?

6 views (last 30 days)
Chad Greene
Chad Greene on 25 Jul 2019
Commented: Walter Roberson on 26 Jul 2019
I ran into an issue today whereby Matlab did NOT throw an error, but I wish it had. I had a 1D array, and I wanted to get just the values corresponding to a few logical true indices, like this:
x = 1:10;
ind = logical([1 0 0 1 0]);
y = x(ind)
y =
1 4
The problem here is I made a mistake: The dimensions of the ind array don't match the dimensions of x, yet Matlab still gave me some numbers anyway. Of course if I let the dimensions of ind exceed the dimensions of x, Matlab appropriately throws an error:
ind = logical([1 0 0 1 0 0 0 0 0 0 1]);
>> x(ind)
The logical indices contain a true value outside of the array bounds.
So why doesn't Matlab throw an error if the dimensions of ind are smaller than the dimensions of x? Is this a bug, or is there some value that I'm not seeing?

Answers (1)

Walter Roberson
Walter Roberson on 25 Jul 2019
Edited: Walter Roberson on 25 Jul 2019
Logical indices are always internally padded with false if they are smaller than what is being indexed (except that the padding isn't actually done)
Also it is acceptable to access an array with a logical vector larger than the array provided that none of the entries past the actual size are true.
I do not have a current reference for this but I believe accessing with a shorter vector used to be documented.
Walter Roberson
Walter Roberson on 26 Jul 2019
I see people using X(L) as an abbreviation for X(L, 1) where numel(vector L) = size(X, 1). It works because logical indexing with a single subscript L is effectively linear indexing by L(:) and matlab always permits trailing subscripts to be omitted.
It is less common for me to see X(L) with numel(vector L) < size(X, 1). I have, though, occasionally used that myself, such as knowing that the value is to be written into one of the first 3 elements and it having been convenient to calculate which by logical vector. I such cases I could have replaced the subscript with find(L) to avoid the mismatch of size of indexing with a vector shorter than the dimension, but there was no point in bothering to do that.
Generally speaking, if you have a numeric vector K indexing a dimension then X(K) and X(L) should give the same effect where K=find(L), and conversely
L=false; L(K) = true;
should have the same subscripting effect. But with automatic zero extension, numel(L) = max(K) and that ought to be fine without requiring
L(K) = true;
which does not even replicate linear indexing. Should users be forced to use
if max(K) <= size(X, 1)
L(K) = true ;
L(K) = true ;
X(L) = whatever

Sign in to comment.





Community Treasure Hunt

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

Start Hunting!