Deleting zeros in front of a vector

27 次查看(过去 30 天)
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?

采纳的回答

Image Analyst
Image Analyst 2017-9-24
编辑:Image Analyst 2017-9-24
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by