Matlab removing unwanted numbers from array

10,193

Solution 1

To display only non-zero results, you can use nonzeros

iseven = [0     2     0     4     0     6]

nonzeros(iseven)

ans =

     2     4     6

Solution 2

You can obtain such vector without the loop you have:

n(rem(n, 2)==0)
ans =

 2     4     6

However, if you already have a vector with zeros and non-zeroz, uou can easily remove the zero entries using find:

iseven = iseven(find(iseven));

find is probably one of the most frequently used matlab functions. It returns the indices of non-zero entries in vectors and matrices:

% indices of non-zeros in the vector
idx = find(iseven);

You can use it for obtaining row/column indices for matrices if you use two output arguments:

% row/column indices of non-zero matrix entries
[i,j] = find(eye(10));

Solution 3

The code you downloaded seems to be a long-winded way of computing the range

2:2:length(n)

If you want to return only the even values in a vector called iseven try this expression:

iseven(rem(iseven,2)==0)

Finally, if you really want to remove 0s from an array, try this:

iseven = iseven(iseven~=0)
Share:
10,193
Eka
Author by

Eka

Blah Blah Blah

Updated on June 17, 2022

Comments

  • Eka
    Eka almost 2 years

    I have got a matlab script from net which generates even numbers from an inital value. this is the code.

    n = [1 2 3 4 5 6];
    iseven = [];
    for i = 1: length(n);
    if rem(n(i),2) == 0
    iseven(i) = i;
    else iseven(i) = 0;
    end
    end
    iseven
    

    and its results is this

    iseven =
    
         0     2     0     4     0     6
    

    in the result i am getting both even numbers and zeros, is there any way i can remove the zeros and get a result like this

    iseven =
    
             2    4     6
    
  • High Performance Mark
    High Performance Mark over 11 years
    Neat, didn't know about nonzeros.
  • Dan
    Dan over 11 years
    why the find(), why not iseven(iseven==0) = []... or iseven = iseven(iseven~=0) if performance is an issue?
  • High Performance Mark
    High Performance Mark over 11 years
    Good questions @Dan. Go ahead and edit the answer for improved goodness.
  • High Performance Mark
    High Performance Mark over 11 years
    @Dan: I made the edit you suggested, your own attempt seemed to get trapped in review and I couldn't figure out how to approve it.