Should this logical indexing throw an error?
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Walter Roberson
2019-7-25
编辑:Walter Roberson
2019-7-25
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.
3 个评论
Walter Roberson
2019-7-26
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=false(1,size(X,1));
L(K) = true;
which does not even replicate linear indexing. Should users be forced to use
if max(K) <= size(X, 1)
L=false(1,size(X,1));
L(K) = true ;
else
L=false(1,numel(X));
L(K) = true ;
end
X(L) = whatever
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!