Debugging inconsistent matrix indexing
1 view (last 30 days)
Show older comments
I was wondering if you could answer my debugging-related question:
Suppose that my code includes the definition of a matrix, let's say:
X = randn(5,5) (a 2x2 matrix containing random numbers)
..but much later in my code, I accidentally forget that X is a matrix and I write another line of code where I treat it as a vector:
Y = X(5)
This does not cause a syntax error. And I understand why it's not supposed to. The question is one of debugging: Is there a shortcut that would help me easily detect, or warn me, if I accidentally treated some matrix as a vector (or, say, treated a 3-dimensional matrix as a 2-dimensional one, for example)?
I realize that, as a possible solution, I can keep track of my matrix sizes "by hand", and I can just "pay more attention", but I was wondering if there is a specific debugging method for the issue I describe?
Best regards,
0 Comments
Accepted Answer
Jan
on 22 Sep 2015
Matlab allows to handle an array with different numbers of dimensions on purpose. The so called linear indexing is a typical example: You can index an array very efficiently using a single index:
x = rand(2,3);
disp(x(1:6));
Because this is not a bug, but intended behavior, there ist no standard "debugging" method to detect this automatically.
If this method means a bug in your code, using a user defined object would be better: Then you can define manually that a run-time error appears, when the object is indexed with the wrong number of dimension.
6 Comments
Jan
on 23 Sep 2015
Example of a useful purpose of linear indexing: Accesss data on the diagonal of a matrix:
A = rand(5, 5);
A(1:6:25) = 1;
Now the diagonal contains ones and the rest is random. Of course sub2ind would work also.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!