フィルターのクリア

Deleting zeros in front of a vector

21 ビュー (過去 30 日間)
amateurintraining
amateurintraining 2017 年 9 月 24 日
コメント済み: amateurintraining 2017 年 9 月 24 日
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
  1 件のコメント
amateurintraining
amateurintraining 2017 年 9 月 24 日
It worked! Thank you so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by