- 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!