Each arithmetic operator in Matlab has an associated method that gets called when you invoke that operator. For example, the method corresponding to * (matrix multiplication) is called mtimes.
For each operator, you can define a method for variables of type double that shadows the builtin method and modifies its behaviour: in your case, include custom error checking and then call the builtin method.
The advantages of this approach are:
No modification in your code is neccessary: you will use *, *., + etc normally; but their (error-checking) behaviour will change.
When (you think) you're done debugging, you only need to remove your custom methods from the path. This will restore normal behaviour and thus avoid any speed penalty. Later, if you need to debug again, all you need to do is place the modified methods back on the path.
In the following I use * and its associated mtimes as an example. Your new mtimes method should be placed in Matlab's path, in an appropriate folder so that it has precedence over the bulitin mtimes. That means the folder should be up in Matlab's path. Or you can use the current folder, which has precedence over all others.
Within the selected folder create a folder called @double, and in it create a file called mtimes.m. This tells Matlab that your mtimes.m file should be used whenever the * is invoked with double inputs.
The contents of mtimes.m whould be something along the following lines:
function C = mtimes(A,B)
if ndims(A)~=2 || ndims(B)~=2
%// number of dimensions is incorrect
error('MATLAB:mtimes_modified:ndims', ...
'One of the arrays is not a matrix: numbers of dimensions are %i and %i',...
ndims(A), ndims(B));
elseif max(size(A))>1 & max(size(B))>1 size(A,2)~=size(B,1)
%// dimensions are not appropriate for matrix multiplication,
%// or for multiplying by a matrix by a scalar
error('MATLAB:plus_modified:dimagree',...
'Sizes do not match: %i x %i and %i x %i', ...
size(A,1), size(A,2), size(B,1), size(B,2));
else
C = builtin('mtimes', A, B); %// call actual mtimes to multiply matrices
end
Example results:
>> rand(3,4,5)*rand(6,7)
Error using * (line 3)
One of the arrays is not a matrix: numbers of dimensions are 3 and 2
>> rand(3,4)*rand(2,5)
Error using * (line 7)
Sizes do not match: 3 x 4 and 2 x 5
>> rand(3,4)*rand(4,2)
ans =
0.3162 0.3009
1.2628 0.7552
1.2488 0.8559
size()for both matrices.dbstop if errorand Matlab will stop execution exactly where the error occurs. You can see the variable sizes in the variable browser and directly try out your improved code.dbstop if error, very useful command!