Error when creating a tensor from a for loop
Show older comments
I want to write a function that stores calculated values depending on the position in x1, x2 and x3 in a tensor (3D array). My current code works with a regular spacing of 1 between the array values:
F_array = zeros(27, 27, 27);
for x1 = -13:1:13
for x2 = -13:1:13
for x3 = -13:1:13
% F = f(x1, x2, x3);
F_array(x1+14, x2+14, x3+14) = F;
end
end
end
To get more accurate result, I tried to reduce the spacing between the array values to 0.5:
F_array = zeros(53, 53, 53);
for x1 = -13:0.5:13
for x2 = -13:0.5:13
for x3 = -13:0.5:13
% F = f(x1, x2, x3);
F_array(x1+27, x2+27, x3+27) = F;
end
end
end
However, now I get the following error message:
"Index in position 3 is invalid. Array indices must be positive integers or logical values."
I don't see any overall difference in the codes. Can anyone tell me what is causing this problem?
Accepted Answer
More Answers (1)
Sameer
on 2 Jan 2025
Hi @Bruce
The issue arises because the indices in MATLAB must be positive integers. When you change the spacing between the values to 0.5, the indices "x1+27", "x2+27", and "x3+27" become non-integers, which is not allowed for indexing.
To fix this, you need to convert the indices to integers. One way to do this is by scaling the indices appropriately.
You can do this by multiplying the indices by 2 to account for the 0.5 spacing and then adding an offset.
Here's how you can modify your code:
F_array = zeros(53, 53, 53);
for x1 = -13:0.5:13
for x2 = -13:0.5:13
for x3 = -13:0.5:13
% F = f(x1, x2, x3);
idx1 = round((x1 + 13) * 2 + 1);
idx2 = round((x2 + 13) * 2 + 1);
idx3 = round((x3 + 13) * 2 + 1);
F_array(idx1, idx2, idx3) = F;
end
end
end
Hope this helps!
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!