Array indexing output size not consisnent

2 次查看(过去 30 天)
Hi When indexing an array using another array of (linear or logical) indices, the result size is not consistent - is this a bug or a feature?
Example 1
% `A` and `idx` are arbitrary-sized arrays
B = A(idx);
isequal(size(B), size(idx))
What is the answer? In most cases, it is true, except for the case when `A` and `idx` are vectors of different orientation.
Example 2
% `A` is arbitrary array, `idx` is logical the size of `A`
B = A(idx);
size(B)
What's the answer? Again, in most cases it is `[nnz(idx) 1]`, except for the case when `A` is row vector.
Is this inconsistent behavior a documented (where?) feature, or a bug? Because seriously, event if it is intentional, it is a bug. I can image than in toy cases in may seem helpful than one gets vectors the size "they expected", but in all other 99.9% cases, I do not know the dimensionality of the data beforehand - I write code that is supposed to work with arbitrary matrices passed into it so I must do a (usually useless) reshape or IF to make sure that the particular weird 1D case is treated correctly and thus revert the action of the very same reshape or IF that you did in your code to "help me".
Thanks for clarification and discussion, my best, JK

回答(1 个)

Image Analyst
Image Analyst 2016-1-2

If idx is not a 1-D vector, then size(idx) returns an array with the lengths in each direction. A(idx) returns a column vector because if idx was such that it picked out only some of the elements of A, then you'd have an output that has "holes" in it, for example 3 elements might be selected on row 1 and 8 elements selected on row 2. Arrays must be rectangular (all rows have the same number of elements), so to get a result, they must just list all selected in a single 1-D vector.

It's not a bug, it's a feature. In time you will not only get used to it but come to appreciate and even rely on it.

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by