matlab function to return array until 0

1 Ansicht (letzte 30 Tage)
mare413
mare413 am 18 Sep. 2017
Beantwortet: Image Analyst am 18 Sep. 2017
i'm trying to create a function that receives an array and returns the array until a 0, for instance [12, -4, 5, 32, 0, 4, 1, -8] return [12, -4, 5, 32], and if the array contains no 0, return the whole array.
here's what i have so far:
function V = Notzero(V)
V(V==0)=[]
end
I an extremely new to Matlab though i know a bit of js, i believe what i wrote returns the array without the 0s, but im not sure. Any help appreciated

Akzeptierte Antwort

Image Analyst
Image Analyst am 18 Sep. 2017
Try this:
function V = Notzero(V)
zeroIndex = find(V == 0);
if ~isempty(zeroIndex)
V = V(1:zeroIndex-1)
end
end
If it finds a zero, it redefines V. If it doesn't find a zero, zeroIndex is empty and it doesn't go into the "if" block and so V is returned completely unchanged.

Weitere Antworten (0)

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by