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.m99 chars5 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
.
gistlibby LogSnag