Clear Filters
Clear Filters

change equal values in a column to nan

1 view (last 30 days)
I have matrix with several columns and rows. Most of the columns are like (1.02 1.05 1.03 1.04 1.04 1.04 1.04 .. 1.04). No I would like to search in my matrix in each column the point from where the following numbers in the column are equal change the second until the last value to nan.
As an example I would like to change (1.02 1.05 1.03 1.04 1.04 1.04 1.04 .. 1.04) to (1.02 1.05 1.03 1.04 nan nan nan ... nan).
But there are some columns that don't have a point from where the column has the same value until the end.
Thank you for your help.

Accepted Answer

John Chilleri
John Chilleri on 6 Feb 2017
Edited: John Chilleri on 8 Feb 2017
Try this:
% Given matrix A
for i = 1:size(A,2) % go through each column
for j = 2:size(A,1) % through elements in column
if (sum(A(j-1,i) == A(j:end,i)) == size(A,1)-j+1)
A(j:end,i) = NaN;
If you have any questions please ask! This will only replace the values if they're forever equivalent (if it repeats 2,2,2,3, it wont replace the 2,2,2).
Hope this helps!
Jan on 8 Feb 2017
The comparison
if (sum(A(j-1,i) == A(j:end,i)) == length(A(j:end,i)))
is more expensive than required. The length of A(j:end,i) is size(A,1)-j+1. The explicit creation of A(j:end,i) only to determine its length, consumes time.
A simplification:
for j = size(A,1)-1:1 % through elements in column
if A(j,i) == A(j+1,i)
A(j+1,i) = NaN;
John Chilleri
John Chilleri on 8 Feb 2017
Edited code to include Jan Simon's size(A,1)-j+1, thanks!

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!