# How to set bottom repeating elements in matrix to NaN?

1 view (last 30 days)
Sushil Pokharel on 16 Jun 2022
Commented: Voss on 17 Jun 2022
I have matrix of large size and I need to change the bottom repeating elements to nan. For instance:
a = [ 1 2 3 2 1 3
3 1 1 3 1 2
1 2 3 3 2 1
1 2 1 2 1 3
1 2 3 1 2 1];
In this matrix, I want to change the bottom repeating numbers. If the numbers are repeating on top, I don't want to do anything to them. Just want to replace the bottom repeating number by NaNs. Any help will be greatly appreciated.
Thank you.
Sushil Pokharel on 16 Jun 2022
The desire outcomes of the matrix should be
a = [ 1 2 3 2 1 3
3 1 1 3 1 2
NaN NaN 3 3 2 1
NaN NaN 1 2 1 3
NaN NaN 3 1 2 1];

Voss on 16 Jun 2022
a = [ 1 2 3 2 1 3
3 1 1 3 1 2
1 2 3 3 2 1
1 2 1 2 1 3
1 2 3 1 2 1];
to_nan = cummin(a(1:end-1,:) == a(end,:),1,'reverse');
to_nan = to_nan([1:end end],:);
a(to_nan) = NaN
a = 5×6
1 2 3 2 1 3 3 1 1 3 1 2 NaN NaN 3 3 2 1 NaN NaN 1 2 1 3 NaN NaN 3 1 2 1
Voss on 17 Jun 2022
You're welcome!

### More Answers (1)

Dyuman Joshi on 16 Jun 2022
Edited: Dyuman Joshi on 16 Jun 2022
Edited as per a comment
a=[1 2 3 2 1 3
3 1 1 3 1 2
1 2 3 3 2 1
1 2 1 2 1 3
1 2 3 1 2 1];
for j=1:2
for i=2:size(a,1)
if any(a(1:i-1,j)==a(i,j))
a(i,j)=NaN;
end
end
end
a
a = 5×6
1 2 3 2 1 3 3 1 1 3 1 2 NaN NaN 3 3 2 1 NaN NaN 1 2 1 3 NaN NaN 3 1 2 1
Sushil Pokharel on 16 Jun 2022
@Dyuman Joshi you are absolutely right. Sorry for the inconvenience.

R2022a

### Community Treasure Hunt

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

Start Hunting!