For Loop Increment Array
7 ビュー (過去 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 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!