1

I want to find multiple elements of a value in an array in Matlab code. I found the function mod and find, but these return the indices of elements and not the elements. Moreover, I wrote the following code:

x=[1 2 3 4];
if (mod(x,2)==0)
a=x;
end

but this does not work. How can I solve this problem?

1
  • note that you are not using indexes. a=x copies the whole x to a Commented Jan 10, 2017 at 11:06

3 Answers 3

3

Looks like you what to find all multiples of 2 (or any number), you can achieve this using :

a = x( mod(x,2) == 0 ) ;
Sign up to request clarification or add additional context in comments.

Comments

0

When you do a = x, x is still x=[1 2 3 4] regardless if (mod(x,2)==0) is true or false; you can assign a value to (mod(x,2)==0), e.g. val = (mod(x,2)==0), then append/add this value to a new array.

Comments

0

Given a vector numberList = [ 1, 2, 3, 4, 5, 6]; and a number number = 2; you can find indices (position in a vector) of the numbers in the numberList that are a multiple of number using indices = find(mod(numberList, number) ==0);.

If necessary you may display a list of this multiples calling: multiples = numberList(indices).

multiples =

     2     4     6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.