MATLAB Answers

Replacing the zero entry of a vector with its nonzero entries

15 views (last 30 days)
Hassan
Hassan on 20 Feb 2018
Commented: Hassan on 21 Feb 2018
Hello,
Today I have another problem slightly different from my previous question, but they are of the same nature.
Suppose I have a vector A in which there are some zero and nonzero entries. How can I replace the nonzero entries of the vector in such a way that the replacement is done with the closet (left/right index) nonzero entry?
If 0 appears between 2 numbers then we replace it with leftmost nonzero number. For example, if A=[2;0;-1;-2;0;0;4;1], then the replacement is done as follows: the 0 in A(2) is replaced with the number in A(1) (i.e. 2) not A(3); the 0 in A(5) is replaced with the number in A(4) and the zero in A(6) is replaced with the number in A(7).
If it occurs that only 1 entry is nonzero, then we replaced all the zero entries with that nonzero entry. If we have only 2 nonzero entries in the middle of the vector, say k,k+1, then we replaced the 1,2,..,k-1 entries with nonzero entry k,and we replaced the k+2,k+3,...,n with the nonzero entry k+1.
Thank you.
  2 Comments
Hassan
Hassan on 20 Feb 2018
@Jan Simon, yes you are right. I have edit the question. Thank you for the observation.

Sign in to comment.

Answers (2)

Jan
Jan on 20 Feb 2018
Edited: Jan on 20 Feb 2018
I guess, that you want to replace zeros by the nearest non-zero value. Then this is a job for interp1:
z = (A == 0);
A(z) = interp1(find(~z), A(~z), find(z), 'nearest');
To consider leading and trailing zeros:
A(z) = interp1(find(~z), A(~z), find(z), 'nearest', 'extrap');
  9 Comments

Sign in to comment.


Basil C.
Basil C. on 20 Feb 2018
Edited: Basil C. on 20 Feb 2018
  • For your first part
for(i=1:length(A)-1)
if(A(i)~=0 && A(i+1)==0)
A(i+1)=A(i);
end
end
However I wasn't able to figure out the pattern as to why do you want to set the zero in A(6) to the value in A(8)
  • For the second part. If the matrix is B.
% CASE 1
if(find(B)== length(B)/2+0.5)
B(:)=B(length(B)/2+0.5);
% CASE 2
elseif(find(B)== [length(B)/2,length(B)/2+1] )
B(1:length(B)/2)=B(length(B)/2);
B(length(B)/2 +1:length(B))=B(length(B)/2+1);
end
Hope this solves your doubt.
  2 Comments
Hassan
Hassan on 21 Feb 2018
@Basil, the problem with your answer is that it contains looping. I prepare loop-free codes.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!