How to check entries in a Matrix diagonal by diagonal
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Jonas
am 18 Apr. 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
Antworten (1)
Walter Roberson
am 18 Apr. 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!