# [Assignment]Write a function called saddle that finds saddle points in the input matrix M.

144 views (last 30 days)
Yihan Liu on 4 Oct 2019
Commented: Rik on 10 Jan 2020
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 element containing the column index. If there is no saddle point in M, then indices is the empty array.
I am working on this assignment...but i got error feedback all the time,i'm still a noob,so can anyone help me to figure out what is wrong in my program? how to improve it?
Here is my program
[a,~] = size(M);
j = 1;i = 1;
[max_M,~] = max(M,[],2);
count = 0;
for ii = 1:a
[c,d] = find(M==max_M(ii));
[e,f] = size(c);
mi = min(M(:,d));
if(max_M(ii) == mi)
while i<=f
while i<=e
output(j,1) = c(i);
output(j,2) = d(i);
j = j+1;
i = i+1;
count = count+1;
end
end
end
if count>0
indices = output;
else
indices = [];
end
end
end

Rik on 6 Oct 2019

If you use min and max you should be able to avoid loops, which probably currently causes your code to run too slow. What code are you using?

Walter Roberson on 6 Oct 2019
Consider column 7. Suppose you find the minimum value of the column using min. Now find the row indices where the column values are equal to the minimum. There is no point in checking any rows other than those ones, because the other rows cannot possibly have values less than the minimum. Now you can go through just that list of rows and test each one to see whether the row test is satisfied; if it is, then emit that row and column pair.
Yihan Liu on 7 Oct 2019
I rewrite my program by using max&min and this time it works. Thank you so much and I appreciate you guys’ help.

Amandeep Kaur on 8 Jan 2020
[a,~] = size(M);
j = 1;i = 1;
[max_M,~] = max(M,[],2);
count = 0;
for ii = 1:a
[c,d] = find(M==max_M(ii));
mi = min(M(:,d));
if(max_M(ii) == mi)
output(j,1) = c(i);
output(j,2) = d(i);
j = j+1;
i = i+1;
count = count+1;
end
end
if count>0
indices = output;
else
indices = [];
end
end
I am writing this code, it is giving following message

Image Analyst on 8 Jan 2020
Try this:
numPoints = 7;
M = randi(9, numPoints, numPoints)
% M = [1,2,3,4,4,3,2,1] % Sample data
rowMaxima = max(M, [], 2)
colMinima = min(M, [], 1)
[rows, columns] = size(M);
output = false(size(M));
for col = 1 : columns
for row = 1 : rows
if M(row, col) >= rowMaxima(row) && M(row, col) <= colMinima(col)
output(row, col) = true;
end
end
end