How do I declare a for loop with a given number of elements?

1 次查看(过去 30 天)
I have a for loop:
for j=0:0.03
..
end
I want j to run through 100 elements, in ascending order, between 0 and 0.03 (the value 0.03 is hypothetical). Can somebody help me, please?

采纳的回答

John D'Errico
John D'Errico 2021-5-15
编辑:John D'Errico 2021-5-15
I'll only have a loop 5 elements long, as I'm feeling tired right now. :)
jvals = linspace(0,0.03,5);
for j = jvals
disp(j)
end
0 0.0075 0.0150 0.0225 0.0300
You should get the idea how to change it to 100.
Do NOT use j as a matrix index, since MATLAB does not allow non-integer indexes.
If you want a vector index also, then do this:
jvals = linspace(0,0.03,5);
for j = 1:numel(jvals)
disp([j,jvals(j)])
end
1 0 2.0000 0.0075 3.0000 0.0150 4.0000 0.0225 5.0000 0.0300

更多回答(1 个)

DGM
DGM 2021-5-15
consider using linspace()
for j = linspace(0,0.03,100)
% do things
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by