how to separate odd and even elements of a matrix with out using for or while loops.
조회 수: 24 (최근 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.
댓글 수: 0
채택된 답변
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
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.
추가 답변 (2개)
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)
댓글 수: 0
Walter Roberson
2015년 5월 23일
are_they_odd = arrayfun(@isodd, A);
odd_ones = A(are_they_odd);
even_ones = A(~are_they_odd);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!