nik
nik

Reputation: 143

Matlab 2D-Array indexing and replacing

Given array Array_in of size m*n and R of size s*2. Each row in array R corresponds to the starting and ending values of the first column of Array_in and the corresponding column elements in Array_in i.e from Array_in(:,2:end) should not be changed and all remaining elements are replaced by NaN. The first column of the output Array_out is same as the Array_in. The number of rows of array R changes. In the following example the number of rows are assumed to be 2.

Array_in = [0 0.1;1 0.8;2 0.5;3 0.2;4 0.3;5 0.6;6 0.8;7 1;8 1.2;9 1;10 0.1]; R = [2 3;6 9];

R 1st row: should be considered as 2:3 = [2 3]; R 2nd row: as 6:9 = [6 7 8 9]; all the rows i.e [2 3 6 7 8 9] should be retained and and the expected output is:

Array_out = [0 NaN;1 NaN;2 0.5;3 0.2;4 NaN;5 NaN;6 0.8;7 1;8 1.2;9 1;10 NaN];

How can this be done?

Upvotes: 0

Views: 80

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

ind = ~any( bsxfun(@ge, Array_in(:,1).', R(:,1)) & ...
            bsxfun(@le, Array_in(:,1).', R(:,2)) );
Array_out = Array_in;
Array_out(ind,2:end) = NaN;

Upvotes: 2

Divakar
Divakar

Reputation: 221564

Try this -

t1 = bsxfun(@times,1:size(Array_in,1),ones(size(R,1),1))
t2 = bsxfun(@ge,t1,R(:,1)) & bsxfun(@le,t1,R(:,2))
ind = ~any(bsxfun(@eq,Array_in(:,1),find(any(t2))),2)

Array_out  = Array_in;
Array_out(ind,2:end)=NaN

Upvotes: 2

Related Questions