How can I make a for loop that goes from -10 : 10?
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mollie Seidner
am 21 Jun. 2018
Beantwortet: Walter Roberson
am 21 Jun. 2018
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 21 Jun. 2018
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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!