How to check entries in a Matrix diagonal by diagonal
4 次查看(过去 30 天)
显示 更早的评论
n=21; %three states: blipped(2- or some other marker), not blipped (1), empty (0)
blipped=2;
notblipped=1;
empty=0;
A=randi(2,n)-1; %WE CAN SET UP THE MATRIX IN WATEREVER WAY WE WANT AND DESIGN AN ALGORITHM OF WIPING OUT "1"S IN WHATEVER WAYS POSSIBLE
%Approach 2
%Check the cells of matrix diagonally
for i=2:n-1
if A(i-1,i-1)+A(i-1,i)+A(i-1,i+1)+A(i,i-1)+A(i,i)+A(i,i+1)...
+A(i+1,i-1)+A(i+1,i)+A(i+1,i+1)>=3
A(i,i)=0; %First loop through diagnal elements
end
for j=1:n-3
if A(i-1,i-j-1)+A(i-1,i-j)+A(i-1,i-j+1)+A(i,i-j-1)+A(i,i-j)+A(i,i-j+1)...
+A(i+1,i-j-1)+A(i+1,i-j)+A(i+1,i-j+1)>=3
A(i,i-j)=0; %Loop through elements below the diagonal
end
if A(i-1,i+j-1)+A(i-1,i+j)+A(i-1,i+j+1)+A(i,i+j-1)+A(i,i+j)+A(i,i+j+1)...
+A(i+1,i+j-1)+A(i+1,i+j)+A(i+1,i+j+1)>=3
A(i,i+j)=0; %Loop through elements above diagonal
end
end
end
disp(A);
I am trying to first loop through elements on the diagonal and then the ones on the subdiagonals. However, my code does not run in matlab. In addition, I am wondering how to deal with boundary conditions? In each "if" statement, I have analyzed eight neighboring entries, however, this does not apply to boundary entries. Just wondering if someone could help with this? Thanks a lot.
2 个评论
Jonas
2021-4-18
i'am not sure what exactly you want to achieve, but maybe you should have a look at the diag() function which can easily give you the diagonal and subdiagonal elements of a matrix
回答(1 个)
Walter Roberson
2021-4-18
[nrow, ncol] = size(A);
count_around = @(A,R,C) sum(A(max(1,R-1:R+1):min(nrow,R-1:R+1), max(1,C-1:C+1):min(ncol,C-1:C+1))) - A(R,C));
Now you can apply
count_around(A,i,j)
sliding i and j in whatever pattern you want.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!