Division of numbers and arrange??
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (3)
Abderrahim. B
el 13 de Jul. de 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
0 comentarios
KSSV
el 13 de Jul. de 2022
Editada: KSSV
el 13 de Jul. de 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)
0 comentarios
Steven Lord
el 13 de Jul. de 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=[]
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)
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.
0 comentarios
Ver también
Categorías
Más información sobre Time-Frequency Analysis en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!