change equal values in a column to nan

2 Ansichten (letzte 30 Tage)
FC93
FC93 am 6 Feb. 2017
Kommentiert: John Chilleri am 8 Feb. 2017
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.

Akzeptierte Antwort

John Chilleri
John Chilleri am 6 Feb. 2017
Bearbeitet: John Chilleri am 8 Feb. 2017
Hello,
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;
break;
end
end
end
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!
  3 Kommentare
Jan
Jan am 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;
else
break;
end
end
John Chilleri
John Chilleri am 8 Feb. 2017
Edited code to include Jan Simon's size(A,1)-j+1, thanks!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by