Given that a=[1;4.2;3​;pi;8;7;62​;50;23;17]​; Please use vector b to represent all the even elements in vector a (b=[8;62;50])?

1 view (last 30 days)
Given that a=[1;4.2;3;pi;8;7;62;50;23;17]; Please use vector b to represent all the even elements in vector a (b=[8;62;50])?
someone can help me how to fix it below ?
a=[1;4.2;3;pi;8;7;62;50;23;17];
n=length(a);
b=zeros(n,1);
t=0;
for m=1:n
if rem(a(m),2)==1
t=t+1;
b(t)=a(m);
end
end
b(t+1:n)=[];

Answers (1)

KSSV
KSSV on 24 Nov 2020
Use modto get your even numbers.
a = [1; 4.2; 3; pi; 8th; 7; 62; 50; 23; 17];
idx = mod (a, 2);
iwant = a (idx == 0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!