MATLAB: How to delete zeros from a vector and place it again in that vector

matrixzeros

I have a vector like,
A = [2000 -1000 0 0 0 2000 -1000 0 0 0 2000 -1000 0 0 0 1000]';
For removing zeros, I did,
B = A(A ~= 0);
Now, I want the same vector A from B. Is there any MATLAB functions available or I need to code it?
Thank you.

Best Answer

Once you've thrown away the zeros, they're gone -- there's no way of knowing where they were in the original A from B alone.
To do this you'll have to save the locations of the zeros in A (or non-zero, one is just the complement of the other) as well as total length in order to rebuild the vector from the pieces.
iNZ=find(A); % nonzero locations in A
lA=length(A); % total length
with those additional pieces of information and B, then
A=zeros(1,lA); A(iNZ)=B;
will reproduce A. But, again, w/o the additional info it's not possible to rebuild A precisely; too little information remains.
ADDENDUM
Actually, you can do it with only one additional variable; if you save the logical array instead of the locations only, then you have the length of the original array implicitly.
iNZ=(A~=0); % logical array instead of vector of locations
then, having B and iNZ
A(iNZ)=B;
will reconstruct A. Of course, since size(iNZ) == size(A), you might as well just save A to begin with. :)