calculate equality between adjacent elements in matrix

조회 수: 1 (최근 30일)
fatema saba
fatema saba 2015년 11월 17일
답변: Andrei Bobrov 2015년 11월 17일
Hello I have matrix A like that:
A=[7 7 3 5 6;1 1 7 5 6;6 6 5 5 5;1 1 3 3 3;1 1 7 7 7]
I want to move from this matrix 2 times. first from left to right and second from up to bottom. then on the baisis of these movements and equality between adjacent elements, matrix B1 and B2 are composed respectively. it means if from left to right movement adjacent elements are equal, the value of corresponding element in matrix B1 is 1. for example in this sample data B1 is like that:
B1=[1 0 0 0;1 0 0 0;1 0 1 1;1 0 1 1;1 0 1 1]
Also matrix B2 is composed on the basis of up to bottomn movement like that:
B2=[0 0 0 1 1;0 0 0 1 0;0 0 0 0 0;1 1 0 0 0]
I hope it is clear. Thank you

채택된 답변

Kirby Fears
Kirby Fears 2015년 11월 17일
편집: Kirby Fears 2015년 11월 17일
You can create a logical matrix (1 for true, 0 for false) by simply checking equality:
B1 = ( A(:,2:end) == A(:,1:end-1) );
B2 = ( A(2:end,:) == A(1:end-1,:) );
The equality check with "==" operates element by element to return B1 and B2 as you requested.
If you want to check for approximate equality instead of precise equality, you can set a tolerance value and use subtraction in a similar manner.
tol = 1e-8; % Set tolerance
B1 = abs( A(:,2:end) - A(:,1:end-1) ) < tol;
B2 = abs( A(2:end,:) - A(1:end-1,:) ) < tol;
Hope this helps.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2015년 11월 17일
B1 = diff(A,[],2)==0;
B2 = diff(A)==0;

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by