how to separate odd and even elements of a matrix with out using for or while loops.

28 次查看(过去 30 天)
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.

采纳的回答

Andrei Bobrov
Andrei Bobrov 2015-5-23
t_odd = rem(A,2) ~= 0;
namber_odd = A(t_odd);
namber_even = A(~t_odd);
  3 个评论
Ugo Bruzadin Nunes
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.

请先登录,再进行评论。

更多回答(2 个)

Thomas Nguyen
Thomas Nguyen 2018-4-6
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)

Walter Roberson
Walter Roberson 2015-5-23
are_they_odd = arrayfun(@isodd, A);
odd_ones = A(are_they_odd);
even_ones = A(~are_they_odd);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by