Info

This question is closed. Reopen it to edit or answer.

Can I have a code that detects # of element transitions and return a matrix that has only rows of minimum element transitions?

3 views (last 30 days)
I have A=[1 0 0 2;1 0 2 2;2 0 1 2;0 0 0 2];
I want a code that eliminates the rows that have multiple element changes compared to other rows:
so in A, first row and second row has only one element change 3rd element ((I call it element transition)) so the code will return a new matrix B that has only the first two rows;
B=[1 0 0 2;1 0 2 2]

Answers (2)

James Tursa
James Tursa on 14 Sep 2016
Edited: James Tursa on 14 Sep 2016
Assuming you compare a row to the previous row and allow at most one element to change, you can use the results of diff(A), count the number of elements that have changed, and discard all rows that have more than 1 change. E.g., (assuming A is not empty)
B = A([true;~(sum(logical(diff(A,1,1)),2)>1)],:);
  1 Comment
JacobM
JacobM on 15 Sep 2016
Great!
Should we have a reference to compare to? I am thinking if MATLAB can find the minimum transitions among all, so it may be useful if I compare all rows to each other, i.e row 2, 3 , 4 are compared to 1 then row 3, 4 compared to 2 and so on. So by that I am certain that the returned row has minimum #transition of all elements compared to all rows, does this make sense? what do you think?

Andrei Bobrov
Andrei Bobrov on 15 Sep 2016
...row 2, 3 , 4 are compared to 1 then row 3, 4 compared to 2 and so on...
C = squeeze(sum(bsxfun(@minus,A,permute(A,[3,2,1]))~=0,2));
[ii,jj] = find(min(C(:)) == C);
B = arrayfun(@(x,y)A([x,y],:),jj,ii,'un',0);

This question is closed.

Community Treasure Hunt

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

Start Hunting!