Division of numbers and arrange??

2 views (last 30 days)
Nate
Nate on 13 Jul 2022
Answered: Steven Lord on 13 Jul 2022
A=[2 8 14 20 22 26 32 38 44 45]
Divisible=[]
NotDivisible=[]
for index=1:1:size(a,2)
b=a(index)
if mod(b,4)==0
Divisible=[Divisible;b]
else mod(b,4)~=0
NotDivisible=[NotDivisible;b]
end
end

Answers (3)

Issa
Issa on 13 Jul 2022
A=[2 8 14 20 22 26 32 38 44 45]
Divisible = [] ;
NotDivisible = [] ;
for index = 1:length(A)
b = A(index) ;
if mod(b,4)== 0
Divisible = [Divisible;b] ;
else
NotDivisible = [NotDivisible;b] ;
end
end
Divisible
NotDivisible

KSSV
KSSV on 13 Jul 2022
Edited: KSSV on 13 Jul 2022
% With loop
A=[2 8 14 20 22 26 32 38 44 45]
Divisible=[] ;
NotDivisible=[]
for index=1:length(A)
b=A(index) ;
if mod(b,4)==0
Divisible=[Divisible;b]
else
NotDivisible=[NotDivisible;b]
end
end
% No loop needed
idx = mod(A,4) ;
D = A(idx==0) ;
ND = A(idx~=0)

Steven Lord
Steven Lord on 13 Jul 2022
While you can do it this way, there are a couple potential improvements you could make (including one that eliminates the loop entirely, though I recognize that your homework assignment probably requires you to use a loop.)
A=[2 8 14 20 22 26 32 38 44 45];
Divisible=[]
Divisible = []
NotDivisible=[]
NotDivisible = []
With this approach, each time you assign a value to either Divisible or NotDivisible, MATLAB needs to find a block of memory that's large enough to hold what's already in that variable plus the new element, copy the existing contents to that new memory, and finally add in that new element.
It's like finding space on your bookshelf for the first book in a series, then needing to move it down two shelves where there's room for the first two books, then moving it to the top shelf where there's space for the whole trilogy.
Instead, I'd keep track of whether or not the number is divisible and use logical indexing afterwards to extract all the divisible elements in one operation.
isDivisible = false(size(A));
Now if an element is divisible, just change the existing value that element in isDivisible from false to true. I'll do this for some random values just for demonstration.
isDivisible([1 4 9]) = true;
Now use isDivisible (and its complement) to pull some of the elements from A.
D = A(isDivisible)
D = 1×3
2 20 44
ND = A(~isDivisible)
ND = 1×7
8 14 22 26 32 38 45
Your task, should you choose to use this approach, is to figure out how to update isDivisible. There's a loop-based approach you could use or a vectorized approach.

Products

Community Treasure Hunt

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

Start Hunting!