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

hsvhsicv  于 2023-10-23  发布在  Matlab
关注(0)|答案(1)|浏览(272)

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

  1. function indices = saddle(M)
  2. % saddle point element who value >= to everything it in its row, and <= every element in its column
  3. % indicies has two columns, each row of indicies corresponds to saddle point
  4. indices = [];
  5. a = min(M);
  6. b = max(M');
  7. for xx = 1:size(M,1)
  8. for yy = 1:size(M,2)
  9. if M(xx,yy) == a(yy) && M(xx,yy) == b(xx)
  10. indices = [indices; xx, yy] ;
  11. end
  12. end
  13. end
  14. end

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

  1. function indices = saddle(M)
  2. % saddle point element who value >= to everything it in its row, and <= every element in its column
  3. % indicies has two columns, each row of indicies corresponds to saddle point
  4. isVector = (size(M,1) == 1 && size(M,2) > 1);
  5. indices = [];
  6. a = min(M);
  7. b = max(M');
  8. for xx = 1:size(M,1)
  9. for yy = 1:size(M,2)
  10. if isVector == 0
  11. if M(xx,yy) == a(yy) && M(xx,yy) == b(xx)
  12. indices = [indices; xx, yy] ;
  13. end
  14. else
  15. if M(1, yy) == max(M)
  16. indices = [indicies; 1, yy];
  17. end
  18. end
  19. end
  20. end
  21. end

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

xdnvmnnf

xdnvmnnf1#

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

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

相关问题