find all even numbers in an array in matlab

To find all even numbers in an array A in Matlab, you can use the mod function to check if each element in A is divisible by 2. If the remainder is 0, then the element is even.

main.m
A = [3 4 5 6 7 8];
even_indices = mod(A,2)==0;
even_numbers = A(even_indices);
disp(even_numbers);
99 chars
5 lines

In this code, mod(A,2)==0 creates a logical array where each element is true if the corresponding element in A is even or false if it is odd. We store that array in even_indices.

We then use even_indices to index into the original array A and retrieve only the even numbers. Finally, we use disp to output the even numbers to the console.

Executing this code will output 4 6 8 to the command window, which are the even numbers in A.

related categories

gistlibby LogSnag