Simple question for using 'for loop'
Mostrar comentarios más antiguos
I want to use 'for loop' to generate a =[2 2^3 2^5 2^7 2^9].
this is my first solution.
for n = 1:2:10 %This is my homework request.I can't change this.
a(n) = 2^n
Z = find(a == 0)
a(Z) = []
end
disp(a)
And this one is my second solution.
for n = 1:2:10
a(n) = 2^n
if a(n) == 0 %I want to use logical operation to find out that variable in 'a' is equal zero.And asign these varaible =[].
a(n) = []
end
end
disp(a)
Why second solution is wrong?
How do I fix it?
Respuesta aceptada
Más respuestas (2)
a = zeros([],1) ;
c = 0 ;
for n = 1:2:10 %This is my homework request.I can't change this.
c = c+1 ;
a(c) = 2^n ;
end
disp(a)
Sreedhar Arumugam
el 7 de Sept. de 2021
Editada: Sreedhar Arumugam
el 8 de Sept. de 2021
Your code always iterates over the odd indices from 1 to 10.
Line 2 of your code -> a(n) = 2^n stores the values in a(1), a(3), a(5) and so on.
The logic that you are using in the second solution will not work, as the code will never run into a 0. The code only iterates over odd indices, and since the 0s are only stored in even indices, they will not be removed from the final array.
In your first solution, the code produced the correct output as find(a==0) returns all the indices that contain 0. So it did not matter that you were never visiting these indices directly through your loop.
The following code would be a fix to your second solution :
b = 2:2:10-1 % This array contains all the even indices till 10 (excluding 10 itself)
for n = 1:2:10 % This is my homework request.I can't change this.
a(n) = 2^n
end
a(b) = []
disp(a)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!