필터 지우기
필터 지우기

In my a for loop where I eg need to go from 1 to 11, and want to make my step size 4 what happens when the computer have to make the last step and it goes over 11?

조회 수: 4 (최근 30일)
for 1:2:11 rest of code

답변 (1개)

John D'Errico
John D'Errico 2018년 2월 6일
편집: John D'Errico 2018년 2월 6일
Why not try it? You can see the behavior from one line of code.
1:4:11
ans =
1 5 9
So if the increment takes you past the endpoint, you do not get 11, or 13. You get up to the step that did not exceed the endpoint.
In fact, if the start point is itself above the end point, with a positive step, you get an empty. So the for loop would not iterate at all.
2:1:0
ans =
1×0 empty double row vector
As you can see, running this code never goes through the loop even once.
for i = 2:1:0
'sdfghwrhrt'
end
  댓글 수: 3
Image Analyst
Image Analyst 2018년 2월 6일
Then you need to create an array with linspace and index into it. For example:
numSteps = 30; % Whatever you want!
v = linspace(1, 11, numSteps);
for k = 1 : length(v)
thisV = v(k);
% Now put code to use thisV in your computations.
end
thisV will be 1 at the first iteration, and 11 at the last iteration. Basically linspace takes the first value, the last value, and the number of steps you need: v = linspace(startValue, endValue, numberOfSteps)
John D'Errico
John D'Errico 2018년 2월 6일
If you always want some fixed number of steps, then linspace is of course the correct answer. But that won't insure a given increment. The increment from linspace will usually be some very arbitrary looking number.
If you know the desired increment, then colon is correct. But colon cannot insure that it hits the end point. Thus a call like
0:2:5
Will ALWAYS generate even numbers. That the end point is an odd number will never cause it to generate an odd number.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by