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,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.
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++. 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). the run time is O(1)
of course.
row = given row argument (for example 1)
col = given column argument (for example also 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.
If your 2D matrix contains Wdt columns and Hgt rows, then indexes of neighbours of k-th element are
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
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.