Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing selective numbers with NaNs

I have eight columns of data. Colulmns 1,3, 5 and 7 contain 3-digit numbers. Columns 2,4,6 and 8 contain 1s and zeros and correspond to 1, 3, 5 and 7 respectively. Where there is a zero in an even column I want to change the corresponding number to NaN. More simply, if it were

155            1           345           0
328            1           288           1
884            0           145           0
326            1           332           1
159            0           186           1

then 884 would be replaced with NaN, as would 159, 345 and 145 with the other numbers remaining the same. I need to use NaN to maintain the data in matrix form. I know I could use

data(3,1)=Nan; data(5,1)=Nan

etc but this is very time consuming. Any suggestions would be very welcome.

like image 251
user3560490 Avatar asked Jan 10 '23 16:01

user3560490


1 Answers

Approach 1

a1 = [
    155            1           345           0
    328            1           288           1
    884            0           145           0
    326            1           332           1
    159            0           186           1]

t1 = a1(:,[2:2:end])
data1 = a1(:,[1:2:end])

t1(t1==0)=NaN
t1(t1==1)=data1(t1==1)

a1(:,[1:2:end]) = t1

Output -

a1 =

   155     1   NaN     0
   328     1   288     1
   NaN     0   NaN     0
   326     1   332     1
   NaN     0   186     1

Approach 2

[x1,y1] = find(~a1(:,[2:2:end]))
a1(sub2ind(size(a1),x1,2*y1-1)) = NaN
like image 83
Divakar Avatar answered Jan 18 '23 15:01

Divakar