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!