Deleting zeros in front of a vector
조회 수: 25 (최근 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?
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!