Replacing the zero entry of a vector with its nonzero entries
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2018-2-20
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.
回答(2 个)
Jan
2018-2-20
编辑:Jan
2018-2-20
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 个评论
Basil C.
2018-2-21
I guess your latest solution should solve the problem.
Nice approach by using interp1 @Jan Simon. Learnt something new.
Basil C.
2018-2-20
编辑:Basil C.
2018-2-20
- 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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!