how to separate odd and even elements of a matrix with out using for or while loops.
32 views (last 30 days)
Show older comments
a function that takes a matrix A of positive integers as an input and returns two row vectors. The first one contains all the even elements of A and nothing else, while the second contains all the odd elements of A and nothing else, both arranged according to column-‐major order of A. without using for loops or while loops.
i am using this approach, where r vector contains the row position of odd elemets and c vector contains the coloumn position of odd elements
function [o e] = separate_by_two(A)
B = mod(A,2)
[r c] = find(B);
now dont know how to make a vector conatining all the odd and even elements.
0 Comments
Accepted Answer
Andrei Bobrov
on 23 May 2015
t_odd = rem(A,2) ~= 0;
namber_odd = A(t_odd);
namber_even = A(~t_odd);
3 Comments
Ugo Bruzadin Nunes
on 5 Jun 2022
This is a beautiful answer. ~ means opposite. The first line collects all divisions by 2 that the remainders are not 0, makes into a bollean 1 or 0 array. The second line gets all the numbers that are odds, the second gets all the numbers that are not odds.
More Answers (2)
Thomas Nguyen
on 6 Apr 2018
Code:
function[] = sortEvenOdd(A)
%This is the main function:
[Aodd,Aeven] = sort(A); %calling the local func
disp('Even numbers of matrix A: '); %display message
disp(Aeven); %display the even row array
disp('Odd numbers of matrix A: '); %display message
disp(Aodd); %display the odd row array
end%sortEvenOdd()
function[Aodd,Aeven] = sort(A)
%This is the local function:
even = rem(A,2) == 0; %even is a logical array that takes value 1 for every even int element of A (else 0)
Aeven = A(even);
Aodd = A(~even);
end%sort()
Sample input for A (Prefered: entered in the command window): A=[1 4 5 6 2 6 7 3 64 5 4 1 7] or A = randi([1 50],1,15)
0 Comments
Walter Roberson
on 23 May 2015
are_they_odd = arrayfun(@isodd, A);
odd_ones = A(are_they_odd);
even_ones = A(~are_they_odd);
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!