How to create a for loop in function with a step size as input?

My current function is:
. .
.
x is supposely to run from 765 to 805 with myself individually keying in the step size
X Eg. 765 -> 770 -> 775 -> 780 .... (step size: 5)
765 -> 767 -> 769 -> 771 .... (step size:2)
.
.
.
765 -> 765.1 -> 765.2 -> 765.3 (step size:0.1)
.
is repetitive procedure.
So Im thinking of changing X as the input of step size and 765 to 805 already implemented in the function. But Im foreign to the command of for loop.
Anyone can help? Will greatly appreciate it! Thanks!

 채택된 답변

Geoff Hayes
Geoff Hayes 2014년 10월 23일
You may be able to avoid the for loop altogether and just pass in a vector of the values from 765 to 805. This should work since your code is already set for element wise operations (due to the presence of the periods). Try the following
stepSize = 5;
x = 765:stepSize:805;
y = 42;
wavelengths = test(x,y);
We initialize x to be a vector that starts at 765, has a step size of 5, and ends at 805, which is just
x =
765 770 775 780 785 790 795 800 805
You should be able to adapt the above for variable step sizes.

댓글 수: 3

hithere
hithere 2014년 10월 23일
편집: hithere 2014년 10월 23일
Sorry. Do you mean typing this in the command window. Oh the element wise operation is because y is actually a 729x1 variable.
I tried doing this:
.
stepSize = 5;
x = 765:stepSize:805;
[wavelengtha] = test(x,y);
.
But it doesnt work.
.
The error returned was
.
??? Error using ==> minus
Matrix dimensions must agree.
Error in ==> test at 3_
wavelengtha = 1./ ((1./x)-(y/10^7));
Since y is a vector (an important fact!) then the above won't work, and so you can use a for loop. You may as well change your function signature to accept the minimum and maximum bounds on x, the step size, and y
function [wavelengths] = test(minx,maxx,stepx,y)
% set the x values
x=minx:stepx:maxx;
% pre-size wavelengtha
wavelengths = zeros(size(y,1),length(x));
for k=1:length(x)
wavelengths(:,k) = 1./((1./x(k))-(y/10^7));
end
Then, from the Command Window, call the above function as
wavelengths = test(765,805,5,y);
thank you so much!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2014년 10월 23일

댓글:

2014년 10월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by