简体   繁体   English

如何在不使用内置 function(例如“find”“min”)的情况下找到向量 A 的最小值并索引所有最小值并召回重复项?

[英]How to find the minimum of a vector A and index all the minimum values without using inbuilt function such as 'find' 'min' and recall duplicates too?

My A = [10 1 6 8 2 3 1 3].我的 A = [10 1 6 8 2 3 1 3]。 As we can see the minimum value is 1 and is seen twice at index 2 and 7.正如我们所见,最小值为 1,在索引 2 和 7 处出现两次。

My MATLAB code is below:我的 MATLAB 代码如下:

function [m,im] = myMinInd(A)
m = A(1);
im = 1;
    for i = 2:length(A)
        if A(i) < m
            m = A(i);
            im = i;
        end
    end
end
>> A
A =
    10     1     6     8     2     3     1     3
>> [m,im] = myMinInd(A)
m =
     1
im =
     2

My index only shows the first time the '1' appears and not the second time.我的索引只显示“1”第一次出现而不是第二次出现。 Can someone help, please?有人可以帮忙吗?

In your for loop, you need to handle cases where A(i) == m .在您的for循环中,您需要处理A(i) == m情况。 For example, like this:例如,像这样:

function [m,im] = myMinInd(A)
m = A(1);
im = 1;
    for i = 2:length(A)
        if A(i) < m
            m = A(i);
            im = i;
        elseif A(i) == m
            im = [im,i];
        end
    end
end

This causes the output im to be a row vector containing the indices of all minimum values.这导致 output im成为包含所有最小值索引的行向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM