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

28 ビュー (過去 30 日間)
Alisha Ali
Alisha Ali 2015 年 5 月 23 日
編集済み: Jan 2022 年 6 月 5 日
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
Ugo Bruzadin Nunes 2022 年 6 月 5 日
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.
Jan
Jan 2022 年 6 月 5 日
編集済み: Jan 2022 年 6 月 5 日
@Maha Almuaikel: ~ is the not() operator - see: not

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by