MATLAB: How to get rid of zeros in vector ans

functionhomeworkvectorwhile loop

function y = realvalue3(x)
n=1;
while n<= length(x)
if abs(x(n))>=10^-12
y(n)=x(n);
n=n+1;
continue
end
n=n+1;
end
realvalue3([1 -5 2 3 0 10^-13 3 -10^-14])
ans =
1 -5 2 3 0 0 3
How do i make the answer show no zeros? it should show [1 -5 2 3 3]

Best Answer

  • One approach:
    function y = realvalue3(x)
    n=1;
    while n<= length(x)
    if abs(x(n))>=10^-12
    y(n)=x(n);
    n=n+1;
    continue
    end
    n=n+1;
    end
    y = y(abs(y)>0); % <— ADD THIS LINE
    end
    EDIT You can set the threshold to be whatever you want, for example:
    y = y(abs(y)>=1);