필터 지우기
필터 지우기

How to check entries in a Matrix diagonal by diagonal

조회 수: 2 (최근 30일)
Zhukun Wang
Zhukun Wang 2021년 4월 18일
답변: Walter Roberson 2021년 4월 18일
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
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
Zhukun Wang
Zhukun Wang 2021년 4월 18일
First, I am looping through all entries in a matrix. I am trying to loop through diagonal and subdiagonal entries and I want to show that if the sum of a certain entry and its eight neighbors are >=3, then this entry is gonna turn to 0.

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by