Eka
Eka

Reputation: 15002

Matlab removing unwanted numbers from array

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

Upvotes: 2

Views: 10569

Answers (5)

sarika
sarika

Reputation: 1

To remove the all Zeros from the program we can use the following command,and the command is-

iseven(iseven==0)=[]

Upvotes: 0

High Performance Mark
High Performance Mark

Reputation: 78364

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)

Upvotes: 3

angs
angs

Reputation: 439

Add to the end of the vector whenever you find what you're looking for.

n = [1 2 3 4 5 6]; 
iseven = []; % has length 0
for i = 1: length(n);
  if rem(n(i),2) == 0
    iseven = [iseven i]; % append to the vector 
  end
end
iseven

Upvotes: 0

H.Muster
H.Muster

Reputation: 9317

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

iseven = [0     2     0     4     0     6]

nonzeros(iseven)

ans =

     2     4     6

Upvotes: 5

angainor
angainor

Reputation: 11810

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));

Upvotes: 5

Related Questions