How to delete zeros from a vector and place it again in that vector?
Show older comments
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.
2 Comments
Cedric
on 8 Oct 2017
What do you mean by "same vector"? Do you want to re-expand B into A?
Deepti Ranjan Majhi
on 8 Oct 2017
Accepted Answer
More Answers (2)
Image Analyst
on 8 Oct 2017
You can do it if you save the indexes you deleted. Try this
A = [2000 -1000 0 0 0 2000 -1000 0 0 0 2000 -1000 0 0 0 1000]'
nonZeroIndexes = A ~= 0
B = A(nonZeroIndexes)
% Get A back from B.
% If A is unavailable, you're going to at least have
% nonZeroIndexes still available or you can't do it.
k2 = 1;
A2 = zeros(length(nonZeroIndexes), 1); % Preallocate
for k = 1 : length(A2)
if nonZeroIndexes(k)
A2(k) = B(k2);
k2 = k2 + 1;
end
end
A2 % Print to command window.
1 Comment
Deepti Ranjan Majhi
on 8 Oct 2017
dpb
on 8 Oct 2017
"Is there any MATLAB functions available...?"
Actually, there is for the particular case of removing/recovering zeros --
>> B=sparse(A);
>> clear A
>> A=full(B)
A =
Columns 1 through 8
2000 -1000 0 0 0 2000 -1000 0
Columns 9 through 16
0 0 2000 -1000 0 0 0 1000
>>
2 Comments
Deepti Ranjan Majhi
on 9 Oct 2017
Note, of course, that for this case B still "knows about" the zeros and they're not actually gone so that if you use it in an arithmetic expression you'll not get what you might expect/want. What is a better solution depends on what we don't know; the application for B
For example
>> mean(B)
ans =
(1,1) 250
>> mean(A)
ans =
250
>> mean(A(find(A)))
ans =
571.4286
>>
Also in the realm of "are there functions?" is
B=nonzeros(A);
as shorthand for A(find(A)) but again from it alone you can't reconstruct A; it's that requirement that's the kicker and if that's what's necessary unless you're running into other memory issues as noted in first response you might as well in all likelihood just keep the original to begin with as being more efficient overall use of resources.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!