Replacing sample numbers with NaN

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. If there is 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 will be replaced by NaN, as well as 159, 345 and 145, while the remaining numbers will remain unchanged. I need to use NaN to store data in matrix form. I know I can use

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

etc., but it is very time consuming. Any suggestions would be greatly appreciated.

+4
source share
5 answers

, , - .

data = your_mat(:,1:2:end);
valid = your_mat(:,2:2:end);

:

data(~valid)=NaN;

, :

your_mat(:,1:2:end) = data;
+3

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

-

a1 =

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

2

[x1,y1] = find(~a1(:,[2:2:end]))
a1(sub2ind(size(a1),x1,2*y1-1)) = NaN
+4

, , , , !

data(~data(:,2:end))=NaN
+2

. circshift .

A:

AM = false(size(A)); AM(:,2:2:end) = true;

(A==0)&AM , .

A(circshift((A==0)&AM,[0 -1])) = nan;

. ... , , , :

A(circshift(bsxfun(@and, A==0, mod(0:size(A,2)-1,2)),[0 -1])) = nan;

The dirty thing with s bsxfunis creating an online AM mask. I use the oddity test on the index vector for this, bsxfunextends it to the entire matrix A. You can do something else to create this mask, of course.

0
source

Using logical indexing:

even = a1(:,2:2:end);    % even columns
odd  = a1(:,1:2:end);    % odd columns
odd(even == 0) = NaN;    % set odd columns to NaN if corresponding col is 0
a1(:,1:2:end)  = odd;    % assign back to a1

a1 = 
   155     1   NaN     0
   328     1   288     1
   NaN     0   NaN     0
   326     1   332     1
   NaN     0   186     1
0
source

Source: https://habr.com/ru/post/1538743/


All Articles