Debugging inconsistent matrix indexing

1 view (last 30 days)
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,

Accepted Answer

Jan
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
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.
Josu Uusitalo
Josu Uusitalo on 24 Sep 2015
Thanks Jan, yeah your code does look somewhat nicer than for example:
(ones(5,5)-eye(5,5)).*randn(5,5) + ones(5,5)
..which came to my mind as I saw your comment.
Thanks!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!