循环查找最大值而不使用max()

时间:2017-09-21 07:07:08

标签: matlab loops max

我正在尝试迭代MATLAB(不允许在构建函数中使用)来查找某个矩阵中每行的最大值。我已经能够找到整个矩阵的最大值,但我不确定隔离行并找到最大值(再次不使用max())。

我的循环目前看起来像这样:

for i = 1:size(A, 1)
    for j = 1:size(A, 2)
        if A(i, j) > matrix_max
            matrix_max = A(i, j);
            row = i;
            column = j;
        end
    end
end

2 个答案:

答案 0 :(得分:3)

您需要结果向量,而不是单个值。请注意,可以将此初始化为零。 除非您知道自己只有正值,否则不要初始化为零。相反,使用-inf初始化为-inf*ones(...),因为所有值都大于负无穷大。或者(参见底部代码块)初始化为A的第一列。

% Set up results vector, same number of rows as A, start at negative infinity
rows_max = -inf*ones(size(A,1),1);
% Set up similar to track column number. No need to track row number as doing each row!
col_nums = zeros(size(A,1),1);
% Loop through. i and j = sqrt(-1) by default in MATLAB, use ii and jj instead
for ii = 1:size(A,1) 
    for jj = 1:size(A,2)
        if A(ii,jj) > rows_max(ii)
            rows_max(ii) = A(ii,jj);
            col_nums(ii) = jj;
        end
    end
end

请注意,如果矢量化没有违反您的内容,那么就没有内置版本"规则(应该没问题,它充分利用了MATLAB语言),然后你可以删除外部(行)循环

rows_max = -inf*ones(size(A,1),1);
col_nums = zeros(size(A,1),1);
for jj = 1:size(A,2)
   % Get rows where current column is larger than current max stored in row_max
   idx = A(:,jj) > rows_max;
   % Store new max values
   rows_max(idx) = A(idx,jj);
   % Store new column indices
   col_nums(idx) = jj;
end

更好的是,你可以将你的循环缩短1,并初始化为A的第一列。

rows_max = A(:,1);            % Set current max to the first column
col_nums = ones(size(A,1),1); % ditto
% Loop from 2nd column now that we've already used the first column
for jj = 2:size(A,2)
   idx = A(:,jj) > rows_max;
   rows_max(idx) = A(idx,jj);
   col_nums(idx) = jj;
end   

答案 1 :(得分:0)

您可以修改它,如下所示,以获得每行的最大值:

% initialize
matrix_max = zeros(size(A,1),1);  
columns = zeros(size(A,1),1); 

% find max
for i = 1:size(A, 1)
    matrix_max(i) = A(i,1);
    columns(i) =  1;
    for j = 2:size(A, 2)
        if A(i, j) > matrix_max(i)
            matrix_max(i) = A(i, j);
            columns(i) = j;
        end
    end
end