Can I disable linear indexing?
3 次查看(过去 30 天)
显示 更早的评论
I am working with a large number of matrices of varying dimensions and have many times typed in the wrong number of indexes when accessing a matrix but because of linear indexing no crash occurs. Is there a way to disable linear indexing?
Example:
aa = rand(2,3,4,5);
>> aa(1,2,3)
ans =
0.76211
>> aa(1,1,1,1,1)
ans =
0.43666
The above are perfectly legal MatLab command but are probably not what would most often be intended.
To get automatic feedback when I do type in a mistake I have made an accessor function that checks the size of the input matrix and the number of indexes; then returns the appropriate values or calls error(). The need for this is dumb.
I can not group the matrices by size. Being more careful has not reduced my error rate. Adding the matrix size to its variable name helped some but has not eliminated my making mistakes.
Is there a good solution I am missing?
PS. In many other cases I love linear indexing, working with N-dimensional matrices by a single index is great. But here it is causing much wasted time.
0 个评论
回答(2 个)
Matt J
2018-10-25
编辑:Matt J
2018-10-25
No, you cannot disable linear indexing. You could try an object-oriented approach. Define a matrix subclass whose subsref method executes the accessor you have implemented.
I'm a bit surprised that you find yourself using subscripts that often. More often, I find that it is linear and logical indexing that you need in Matlab computation, to avoid lots of inefficient nested for-loops.
3 个评论
Matt J
2018-10-25
编辑:Matt J
2018-10-25
I just want to echo something Walter said, though. Remember that not all mfiles are your mfiles. If you disable linear indexing, even for your own special class, that class will be cut-off potentially from using lots of stock Matlab functions that make use of linear indexing. You also wouldn't be able to do basic things like
>> max(aa(:))
to take the maximum over a multidimensional array. You can do things like
>> max(max(max(max(a))))
but in my opinion that is absurd.
Walter Roberson
2018-10-25
No there is not.
In my opinion it is very unlikely that this will ever been added for any of the fundamental numeric data types, as there is just too much code that works with linear indexing for element-wise operations, and too much code that uses vector indexing (remember, MATLAB does not have true vectors, only linear indexing into a 2D array that happens to be singular on one of the dimensions.)
If this is something you need then probably the appropriate mechanism would be to subclass the numeric datatypes, so that the special rules only apply to variables you designate instead of there being a switch of some sort that applied to every linear access.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!