Division of numbers and arrange??
2 views (last 30 days)
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] ;
NotDivisible = [NotDivisible;b] ;
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];
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)
ND = A(~isDivisible)
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.