【问题标题】:Get elements of a matrix that are greater than sum of their two indices in row major order获取矩阵的元素,这些元素大于它们在行主要顺序中的两个索引的总和
【发布时间】:2026-02-13 12:15:01
【问题描述】:

我正在编写一个名为 large_elements 的函数,它接受一个名为 X 的数组的输入,该数组是一个矩阵或向量。该函数识别X 中大于它们两个索引之和的那些元素。

例如,如果元素X(2,3)6,则该元素将被识别为6 > (2 + 3)。该函数的输出给出了以row-major order找到的这些元素的索引(行和列子)。它是一个正好有两列的矩阵。第一列包含行索引,而第二列包含相应的列索引。

这里是一个例子,语句

indexes = large_elements([1 4; 5 2; 6 0]) 

应该给出这样的输出:

[1 2; 2 1; 3 1]

如果不存在这样的元素, 该函数返回一个 empty array.

我想出了以下代码

function indexes = large_elements(A)
    [r c] = size(A);
    ind = 1;
    for ii = 1:r
        for jj = 1:c
            if A(ii,jj) > ii + jj
                indexes(ind,:) = [ii jj];
                ind = ind + 1;
            else
                indexes = [];
            end
       end  
    end
end

但结果并不如预期。任何帮助将不胜感激。

【问题讨论】:

  • 我已经更新了代码,参数错误 [10 9 8 7 6 5 4 3 2 1] 输出应该是 [1 1;1 2;1 3;1 4]跨度>

标签: arrays matlab for-loop matrix


【解决方案1】:

一种使用bsxfunfindind2sub 的矢量化方法

A = randi(8,5);    %// Your matrix

%// finding sum of the indexes for all elements
indSum = bsxfun(@plus, (1:size(A,1)).', 1:size(A,2));

%// generating a mask of which elements satisfies the given condition (i.e A > indSum)
%// Transposing the mask and finding corresponding indexes
[c,r] = find(bsxfun(@gt, A, indSum).') ;

%// getting the matrix by appending row subs and col subs
out = [r,c]

结果:

输入 A:

>> A

A =

 4     4     7     2     2
 1     3     4     8     3
 8     8     2     8     7
 8     3     4     5     1
 4     1     1     1     1

以行优先顺序输出:

out =

 1     1
 1     2
 1     3
 2     4
 3     1
 3     2
 3     4
 4     1

注意:在这里按行优先顺序获取子项很棘手


这也是你正确的循环方法

[r, c] = size(A);
ind = 0;
indexes = [];
for ii = 1:r
    for jj = 1:c
        if A(ii,jj) > ii + jj
            ind = ind + 1;
            indexes(ind,:) = [ii jj];              
        end
   end  
end

【讨论】:

  • 很好,但是您可以通过在 bsxfun 调用的结果上调用 find 来完全跳过对 ind2sum 的调用,该调用返回已经在 logical 矩阵中的索引。像这样:[c,r] = find( bsxfun(@gt, A, indSum).' ) ;
  • @Hoki,啊!我完全忘记了您可以从find 本身生成行和列子。感谢您纠正我:) 已编辑!
【解决方案2】:

这是因为每当您遇到小于其索引总和的元素时,您都会将数组重新初始化为null。所以输出是null。您不应在 else 条件下将其初始化为 null

【讨论】:

  • 那么可能的方式
  • 不要将indexes = []; 放在else 部分。如果您的 ind 在循环后仍然为 1,请将其放在末尾​​span>
最近更新 更多