我有这段代码向我显示了随机矩阵的最小值和最大值,而没有使用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或loop函数来执行此操作,而我使用的是MATLAB版本2018a
答案 0 :(得分: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);
答案 1 :(得分:0)
您可以通过排序:
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
在内部调用min
和max
。但是,您可以只使用自己的代码来确定最小值和最大值。)< / p>