[英]Efficient method of locating adjacent elements in a matrix
I'm trying to write some code that will locate the elements that are orthogonal to a given entry in a matrix. 我正在尝试编写一些代码来定位与矩阵中给定条目正交的元素。 The output needs to include what the elements are themselves, their indices, and the algorithm needs to work for the edges as well.
输出需要包括元素本身是什么,它们的索引以及算法也需要为边缘工作。 For example, consider
例如,考虑
A = [ 1 2 5 6 7
2 3 1 6 9
3 6 7 8 1 ]
Then if I want the elements adjacent to entry (2,2), the code would return: 然后,如果我想要与条目(2,2)相邻的元素,代码将返回:
[2,2,1,6] %-> these elements are orthogonal to entry (2,2)
[w,x,y,z] %-> where w,x,y,z correspond to the index of the orthogonal entries
%found (they can be linear indices or otherwise).
So I implemented my own function to do this and well, I realized its pretty bad. 因此,我实现了自己的功能来做到这一点,并且很好,我意识到它相当糟糕。 It doesn't seem to consistently work for the edges (although I could try padding the matrix and see if that fixes it-I haven't had a chance yet), and importantly, my code loops over the entire freaking matrix.
它似乎不能始终如一地工作在边缘上(尽管我可以尝试填充矩阵并查看是否可以解决问题-我还没有机会),而且重要的是,我的代码遍历了整个怪异的矩阵。 And so its very inefficient.
因此,它的效率很低。 I was wondering if someone had a quick, efficient way of doing what I've outlined above?
我想知道是否有人可以快速,有效地完成上面概述的工作? MATLAB doesn't seem to have a function for doing this-I've checked.
MATLAB似乎没有执行此操作的功能-我已经检查过了。
I'd appreciate the help. 非常感谢您的帮助。
for(int i = row-1; i <= row+1; i += 2) {
for(int j = col-1; j <= col+1; j += 2) {
if(row>=0 && col>=0 && row < MATRIX_SIZE && col < MATRIX_SIZE)
std::cout << mat[row, col];
}
}
this in a example in c++. 在c ++中的示例中。 the output will not be very clear but this is just an example.
输出不会很清楚,但这只是一个例子。 in programming its assumed the rows/cols in the matrix starts from 0 (not 1) so in your example, the solution you gave will fit the input (1,1) and not (2,2).
在编程时,假设矩阵中的行/列从0(不是1)开始,因此在您的示例中,您给出的解决方案将适合输入(1,1)而不适合(2,2)。 the run time is
O(1)
of course. 运行时间当然是
O(1)
。
row = given row argument (for example 1) row =给定的行参数(例如1)
col = given column argument (for example also 1) col =给定的列参数(例如也为1)
MATRIX_SIZE = the size of the matrix: if the matrix is nxn then MATRIX_SIZE = n, and the last index in each row/col of the matrix is n-1. MATRIX_SIZE =矩阵的大小:如果矩阵为nxn,则MATRIX_SIZE = n,并且矩阵每行/列的最后一个索引为n-1。
If your 2D matrix contains Wdt columns and Hgt rows, then indexes of neighbours of k-th element are 如果您的2D矩阵包含Wdt列和Hgt行,则第k个元素的邻居的索引为
top = k - Wdt // if k > Wdt
bottom = k + Wdt // if k <= Wdt * Hgt - Wdt
right = k + 1 // if (k - 1) mod Wdt > 0
left = k - 1 // if (k - 1) mod Wdt < Wdt - 1
if-expressions are intended to exclude off-edge elements if表达式旨在排除边缘元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.