For Loop Increment Array
16 次查看(过去 30 天)
显示 更早的评论
I am currently in class and trying to do my assignment. For this assignment we have to create a for loop that creates an array of 0 through 20 with the even numbers. I wrote the code according to my lesson but it keeps inserting a 0 between each number in the array. Is there something obvious I am missing?
% for loop example
for i = 0:2:20
A(i+1) = i^2;
B(i+1) = i;
end
1 个评论
Stephen23
2024-7-15
"Is there something obvious I am missing?"
Your code assigns numeric values to the odd elements 1, 3, 5, 7, ... etc.
What numeric value do you expect the even elements 2, 4, 6, 8, ... to have ?
采纳的回答
Steven Lord
2024-7-15
I wrote the code according to my lesson but it keeps inserting a 0 between each number in the array.
It doesn't so much insert a 0 between each number in the array so much as not assigning to certain elements in the array. Let me add a little diagnostic code to what you wrote. I'm also only going to work on A as B has the same behavior and I'm changing the vector over which your for loop operates just so we display fewer lines.
A = zeros(1, 0); % Need to create A prior to the loop
for i = 0:2:6
fprintf("Before assigning to element %d of A, A has length %d.\n", i+1, length(A))
fprintf("Assigning %d to element %d of A.\n", i^2, i+1)
A(i+1) = i^2;
fprintf("After assigning to element %d of A, A has length %d.\n \n", i+1, length(A))
end
A
All the values in the vector over which you're iterating are even. You only ever assign to the elements at locations that are the values in that vector plus 1, so you only ever assign to the odd element locations. But MATLAB can't leave "holes" in the vector, so when it grows the vector it has to fill in the even element locations (that you're skipping over) with something. That something, for a double array, is 0.
To avoid skipping elements, either perform a computation on the value of i to map between the values 0:2:n and the indices 1:m or keep a variable with the index of the next element to fill in.
A = zeros(1, 0);
ivalues = 0:2:6;
C = zeros(1, 0);
nextCloc = 1;
for i = ivalues
fprintf("Assigning %d to element %d of A.\n", i^2, (i/2)+1)
A((i/2)+1) = i^2;
fprintf("Assigning %d to element %d of C.\n", i^2, nextCloc)
C(nextCloc) = i^2;
nextCloc = nextCloc + 1;
end
disp(ivalues)
disp(A)
disp(C)
0 个评论
更多回答(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!