Replacing the zero entry of a vector with its nonzero entries
12 views (last 30 days)
Show older comments
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
Jan
on 20 Feb 2018
The question is strange. You want to replace the nonzero elements by the closest nonzero elements? The same for: "only 1 entry is nonzero, then we replaced all the nonzero entries with that nonzero entry"?
Do you mean that you want to replace the zeros as in the given example? Please edit the question and fix this.
Answers (2)
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
Basil C.
on 21 Feb 2018
I guess your latest solution should solve the problem.
Nice approach by using interp1 @Jan Simon. Learnt something new.
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
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!