필터 지우기
필터 지우기

Simple question for using 'for loop'

조회 수: 12 (최근 30일)
Han Shiang Chuang
Han Shiang Chuang 2021년 9월 5일
댓글: Han Shiang Chuang 2021년 9월 8일
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?

채택된 답변

Walter Roberson
Walter Roberson 2021년 9월 5일
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
Han Shiang Chuang
Han Shiang Chuang 2021년 9월 8일
Thanks for the help! It's clear to me now.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

KSSV
KSSV 2021년 9월 5일
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 2021년 9월 7일
편집: Sreedhar Arumugam 2021년 9월 8일
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)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by