My 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.
My MATLAB code is below:
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. Can someone help, please?
In your for
loop, you need to handle cases where 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.