Deleting zeros in front of a vector

29 views (last 30 days)
I have to solve this problem:
Write a function called unpad, which takes a row vector, removes all zeros at the beginning of the vector, and returns the remaining elements of the vector (i.e., it drops the zeros at the beginning of the vector). Assume that at least one element in the array w is non-zero.
However, I only want to delete the zeros in front of the vector (meaning, not including the zeros IN the vector).
Right now, my code is as follows:
function [ vec ] = unpad( w )
%generates a row vector
% takes a row vector, removes all zeros at the beginning of the vector,
% and returns the remaining elements of the vector
find(w==0)
end
However, this includes value of zero that are also IN the vector. How do I delete the zeros only at the beginning of the vector?

Accepted Answer

Image Analyst
Image Analyst on 24 Sep 2017
Edited: Image Analyst on 24 Sep 2017
Close, but you used find incorrectly. You need to use ~= 0 instead of == 0:
unpad([1,0,0,0,4,4,4,0]) % Test with non leading zeros.
unpad([0,0,0,5,5,5,0,0,6]) % Test with leading zeros.
function vec = unpad( w )
% Takes a row vector, removes all zeros at the beginning of the vector,
% and returns the remaining elements of the vector
index = find(w ~= 0, 1, 'first');
vec = w(index : end);
end

More Answers (0)

Categories

Find more on Multidimensional Arrays 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!