为什么这个函数不接受行向量作为参数?(MATLAB)

hsvhsicv  于 8个月前  发布在  Matlab
关注(0)|答案(1)|浏览(126)

在我正在参加的MATLAB课程的作业中,作业要求创建一个函数,该函数将在矩阵中找到鞍点(行中具有最高值的点,列中具有最低值)。我最初有以下代码:

function indices = saddle(M)
%  saddle point element who value >= to everything it in its row, and <= every element in its column
% indicies has two columns,  each row of indicies corresponds to saddle point 

indices = [];
a = min(M);  
b = max(M'); 

for xx =  1:size(M,1)
    for yy = 1:size(M,2)
        if M(xx,yy) == a(yy) && M(xx,yy) == b(xx)
            indices = [indices; xx, yy] ;  
            
        end
    end
end
end

这适用于任何不是单行向量的矩阵。
我最终用这段代码解决了这个问题:

function indices = saddle(M)
%  saddle point element who value >= to everything it in its row, and <= every element in its column
% indicies has two columns,  each row of indicies corresponds to saddle point 

isVector = (size(M,1) == 1 && size(M,2) > 1);

indices = [];
a = min(M);  
b = max(M'); 

for xx =  1:size(M,1)
    for yy = 1:size(M,2)
        if isVector == 0
            if M(xx,yy) == a(yy) && M(xx,yy) == b(xx)
                indices = [indices; xx, yy] ;  
            end  
        else
            if M(1, yy) == max(M)
                indices = [indicies; 1, yy];
            end
        end
    end
end

end

但是,我只是困惑,为什么最初的代码不会工作。它适用于缩放器,适用于n*1个向量,适用于除行向量之外的任何向量。
此外,任何关于更好的方法来解决这个问题,或清理代码的方法的提示都非常感谢。只是学习MATLAB,很高兴我能够找到一个工作解决方案,但我总是在寻找一些方法来变得更好。谢谢你,谢谢!

xdnvmnnf

xdnvmnnf1#

minmax将返回标量值,而不是每行/列一个值,如果你传递给它们一维数组。如果您不希望发生这种情况,则需要指定尺寸,例如。

a = min(M,[],1);  
b = max(M,[],2); % = max(M.',[],1).'

相关问题