how to remove unwanted zeros from a vector

I have a column vector of the type [ 0 0 0 0 4 5 6 0 0 0 9 9 8 7 6 0 0 0 0 0 0 3 4 4 0 0 0]
Want to remove unwanted zeros to get the form [ 0 4 5 6 0 9 9 8 7 6 0 3 4 4 0]
i -e I don't wana remove all zeros or zeros in the beginning and end. find will not work I guess:

 Accepted Answer

v = [ 0 0 0 0 4 5 6 0 0 0 9 9 8 7 6 0 0 0 0 0 0 3 4 4 0 0 0];
d = [1 diff(v)]; % 0's indicate when the value didn't change
x = d==0 & v==0; % Indexes where value is 0 and didn't change
v(x) = []; % Remove the indexes associated with x

More Answers (2)

a=[ 0 5 0 0 0 0 4 5 6 0 0 0 9 9 8 0 7 6 0 0 0 0 0 0 3 4 4 0]
idx=a==0
ii1=strfind([0 idx],[0 1])
ii2=strfind([idx 0],[1 0])
idy=[];
for k=1:numel(ii1)
idy=[idy ii1(k)+1:ii2(k)]
end
a(idy)=[]

1 Comment

Thank you Azzi for your naswer.It works f9,however I am looking for more simple solution

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!