MATLAB: How to make a for loop that goes from -10 : 10

for loopsrange in for loop

Here are two options for what to do right now….im not sure if either of these are correct or if there is a better way to do it.
for x = range(-10:10)
for y = range(-10:10)
(code goes here)
end
end
or
for x = -10: 1: 10
for y = -10: 1: 10
(code)
end
end

Best Answer

MATLAB does not use range() . Your second version is correct.
However, you will probably want to store the results of each iteration. In this case you would have to store into Output(X+11, Y+11) . In the more general case where you might not be incrementing by 1, you should learn a different pattern:
xvals = -10:.12345:10; %your increments might not be integer so it might be difficult to compute indices
nx = length(xvals);
yvals = randn(size(xvals)); %you might not have any fixed increment at all, might not be ordered
ny = length(yvals);
Output = zeros(nx, ny);
for xidx = 1 : nx
x = xvals(xidx);
for yidx = 1 : ny
y = yvals(yidx);
...
Output(xidx, yidx) = ...
end
end
with this general pattern, the values to be processed do not have to be consecutive or even ordered, but this code will handle all of the combinations.
Related Question