Simple question for using 'for loop'

19 visualizaciones (últimos 30 días)
Han Shiang Chuang
Han Shiang Chuang el 5 de Sept. de 2021
Comentada: Han Shiang Chuang el 8 de Sept. de 2021
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

Walter Roberson
Walter Roberson el 5 de Sept. de 2021
The first time you store into a(1), the second time you store into a(3), then a(5), then a(7), then a(9)
You always store a non-zero value because 2^n is only zero when n is more negative than -1074 (in double precision numbers.) So testing a(n) will never be 0 in your code.
But... you are not storing anything specific into a(2) or a(4) or a(6) or a(8) so those would be 0. They would not be located testing a(n) only, but they would be found with the find()
Hint: you are not required to store at a(n) . You could take n and use it to compute a relative index
  • n = 1 -> index 1
  • n = 3 -> index 2
  • n = 5 -> index 3
  • n = 7 -> index 4
Notice what happens if you add 1 to n and then take half of the result.
  1 comentario
Han Shiang Chuang
Han Shiang Chuang el 8 de Sept. de 2021
Thanks for the help! It's clear to me now.

Iniciar sesión para comentar.

Más respuestas (2)

KSSV
KSSV el 5 de Sept. de 2021
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)
2 8 32 128 512

Sreedhar Arumugam
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 Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by