Effacer les filtres
Effacer les filtres

How to check entries in a Matrix diagonal by diagonal

2 vues (au cours des 30 derniers jours)
Zhukun Wang
Zhukun Wang le 18 Avr 2021
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 commentaires
Jonas
Jonas le 18 Avr 2021
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 le 18 Avr 2021
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.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 18 Avr 2021
[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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by