Discussion of the solution and code
You could employ this three-steps process and implement the solution with sum
, size
and any
and without using any loop
!!
The steps to be followed for such an implementation could be classified into three steps -
Get the sum of the input matrix along rows and columns.
Calculate the distance matrix between all elements of sum along rows against sum along columns.
The is essentially the most important of these steps and you would have otherwise required at least one loop or bsxfun
(for internal replication) to perform this.
Now, the distance matrix calculation here is performed with matrix-multiplication and is a simplified case of this solution to Speed-efficient classification in Matlab
.
For all distance matrix elements, see if there's any element that is zero.
The code to realize the above steps would look something like this -
%// Get the sum of rows and columns into column vectors - A and B respectively
A = sum(M,2)
B = sum(M,1)' %//'
%// Calculate the distance matrix between A and B
nA = size(A,1);
nB = size(B,1);
A_ext(nA,3) = 0;
A_ext(:,1) = 1;
A_ext(:,2) = -2*A;
A_ext(:,3) = A.^2;
B_ext(nB,3) = 0;
B_ext(:,3) = 1;
B_ext(:,1) = B.^2;
B_ext(:,2) = B;
distmat = A_ext * B_ext.'; %//'
%// For all distance matrix values check if any is zero for the final output
out = any(distmat(:)==0)
Sample run and verification
>> M (Sample input matrix)
M =
2 14 3
5 6 7
1 5 5
3 1 2
As can be seen that the sum along the third row is 11
, which is the same as the sum along the first column. Thus, in the distance matrix, at least one element must be zero
.
>> A (Sum along rows)
A =
19
18
11
6
>> B (Sum along columns)
B =
11
26
17
>> distmat (distance matrix between A and B)
distmat =
64 49 4
49 64 1
0 225 36
25 400 121
As estimated earlier, there is one zero at (3,1)
and thus, the final output of any(distmat(:)==0)
would be 1
, which is the expected final result.