matlab function to return array until 0
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Image Analyst
on 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.
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!