how to separate odd and even elements of a matrix with out using for or while loops.
22 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alisha Ali
am 23 Mai 2015
Bearbeitet: Jan
am 5 Jun. 2022
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 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 23 Mai 2015
t_odd = rem(A,2) ~= 0;
namber_odd = A(t_odd);
namber_even = A(~t_odd);
3 Kommentare
Ugo Bruzadin Nunes
am 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.
Weitere Antworten (2)
Thomas Nguyen
am 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 Kommentare
Walter Roberson
am 23 Mai 2015
are_they_odd = arrayfun(@isodd, A);
odd_ones = A(are_they_odd);
even_ones = A(~are_they_odd);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!