- n = 1 -> index 1
- n = 3 -> index 2
- n = 5 -> index 3
- n = 7 -> index 4
Simple question for using 'for loop'
조회 수: 15 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
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
Notice what happens if you add 1 to n and then take half of the result.
추가 답변 (2개)
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)
댓글 수: 0
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!