Replacing the column of array elements with NaN.
10 views (last 30 days)
Given an array A = [0 11; 0.1 2; 0.2 5; 0.3 3; 0.4 6; 0.5 7; 0.6 10; 0.7 4; 0.8 5; 0.9 6; 1 12]; and array x = [0.2,0.4 ; 0.6,0.9];. I would like to manipulate the second column. with respect to the array x. Out_Arr = [0 NaN; 0.1 NaN; 0.2 5; 0.3 3; 0.4 6; 0.5 NaN; 0.6 10; 0.7 4; 0.8 5; 0.9 6; 1 NaN]; Could any one help on this?
Geoff Hayes on 29 May 2014
Edited: Geoff Hayes on 29 May 2014
It seems that the rows of x indicate which ranges of values in A should be preserved, with the rest of the entries in the second column of matrix A set to NaN. A looping solution is as follows:
% pre-allocate array of indices indicating values in A to keep/preserve
keepInA = zeros(size(A(:,2)));
% loop over all rows of x
% find where in the first column of A are the two values for the ith row of x
mems = ismember(A(:,1),x(i,:));
% set that range in keepInA to be all ones indicating all values in that range
% are to be kept (there's is probably a better way to do this)
keepInA(find(mems,1,'first'):find(mems,1,'last')) = 1;
% now just set all those elements in the second row of A to be NaN if they
% are NOT to be kept (i.e. zero)
A(keepInA==0,2) = NaN;
The above assumes that there is no overlap of ranges in x and that those ranges can be found in A. If the assumptions are not true, then the above code would have to be modified.
More Answers (3)
Andrei Bobrov on 29 May 2014
Out_Arr = A;
Out_Arr(all(bsxfun(@lt,A(:,1),x(:,1)')|bsxfun(@gt,A(:,1),x(:,2)'),2),2) = nan;