【问题标题】:Finding coordinates min and max of a matrix without using min/max commands在不使用 min/max 命令的情况下查找矩阵的坐标最小值和最大值
【发布时间】:2019-03-28 09:47:11
【问题描述】:

我有这段代码可以显示随机矩阵的最小值和最大值,而无需使用 min/max 命令:

   m = rand(5,5)*10
    mn = m(1);
    mx = m(1);
    for ii = 2:numel(m)
        if m(ii) < mn
            mn = m(ii);
            imn = ii;
        elseif m(ii) > mx
            mx = m(ii);
            imx = ii;
        end
    end
    disp(mx)
    disp(mn)

我怎样才能找到最小和最大坐标/位置? 我只需要使用函数 for 或循环来执行此操作,并且我使用的是 matlab 版本 2018a

【问题讨论】:

  • imnimx不是已经是最小值/最大值的位置了吗?您在寻找不同的东西吗?
  • BUG在初始化中:mx = m(2);应该是mx = m(1);
  • 我编辑了,看
  • 这里没有问题可以重现或修复,目前还不清楚为什么imximn 不是您要查找的值,您已经计算过了!
  • 我需要从矩阵中找到最小值和最大值的位置 (I,J),使用 for 函数,imx 和 imn 不显示坐标 i j

标签: matlab matrix max min matrix-indexing


【解决方案1】:
A = rand(5,5);
B = A(:);
[B,I] = sort(B);
m_min = B(1);
m_max = B(end);
index_min = I(1);
index_max = I(end);
  • 生成随机数组
  • 将数组转换为向量
  • 对向量进行排序
  • 最大值是最后一项
  • 最小值是第一项

我已修改代码以显示极值索引。等效指数为 可以使用ind2subs找到数组中的坐标

coord_max = ind2subs([5,5], index_max);
coord_min = ind2subs([5,5], index_min);

【讨论】:

    【解决方案2】:

    您可以通过排序来做到这一点:

    function [minVal, maxVal, cMin, cMax] = q52961181(m)
    if ~nargin, m = rand(5,5); end
    sz = size(m);
    [v,c] = sort(m(:), 'ascend');
    % at this point, the *linear* indices of the minimum and the maximum are c(1) and c(end),
    % respectively.
    [x,y] = ind2sub(sz, c([1,end]));
    assert(isequal(numel(x), numel(y), 2)); % make sure we don't have repetitions
    minVal = v(1); maxVal = v(2);
    cMin = [x(1), y(1)];
    cMax = [x(2), y(2)];
    

    或者使用find:

    function [minVal, maxVal, cMin, cMax] = q52961181(m)
    if ~nargin, m = rand(5,5); end
    [minVal,maxVal] = bounds(m,'all'); % "bounds" was introduced in R2017a
    [cMin, cMax] = deal(zeros(1,2));
    [cMin(1), cMin(2)] = find(m == minVal);
    [cMax(1), cMax(2)] = find(m == maxVal);
    

    (此解决方案在技术上是作弊,因为bounds 在内部调用minmax。但是,您可以只使用自己的代码来确定最小值和最大值。)

    【讨论】:

    • 我需要用for函数来做这个
    • @LucasTesch 在这种情况下,1) 请更新问题以说明此要求(考虑到这是 MATLAB 中的错误编码实践); 2) 查看 Cris 对该问题的评论 - 您的解决方案几乎 是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多