Borrar filtros
Borrar filtros

Deleting zeros in front of a vector

21 visualizaciones (últimos 30 días)
amateurintraining
amateurintraining el 24 de Sept. de 2017
Comentada: amateurintraining el 24 de Sept. de 2017
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?

Respuesta aceptada

Image Analyst
Image Analyst el 24 de Sept. de 2017
Editada: Image Analyst el 24 de Sept. de 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

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by