Search Program on this blog

Thursday 27 August 2015

Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem, a saddle point is defined as an element whose value is greater than or equal to every element in its row, and less than or equal to every element in its column. Note that there may be more than one saddle point in M. Return a matrix called indices that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of the row containing the row index of the saddle point and the second column containing the column index. The saddle points are provided in indices in the same order they are located in M according to column-major ordering. If there is no saddle point in M, then indices is the empty array.

function indices = saddle(M)
%Input M is a matrix
%Output indices is a matrix of exactly two columns
%Example indices = saddle([1 2 3;4 5 6;7 8 9])
indices=[];
[m,n]=size(M);
for i=1:n
    for j=1:m
        a=min(M(:,i));  %minimum element in a column
        b=max(M(j,:));  %maximum element in a row
        if M(j,i)==a && a==b 
            indices=[indices;j i];
        end
    end
end

3 comments: