필터 지우기
필터 지우기

How do I make a function out of my for loop?

조회 수: 3 (최근 30일)
Tyler Johnson
Tyler Johnson 2016년 9월 19일
답변: Walter Roberson 2016년 9월 20일
I have a main file with a for loop that computes a value based on a variable that is initialized in the same file above the for loop.
stick = [totalRun totalCrash];
[ROWS,COL] = size(stick);
total = sum(stick);
normalizedStick = stick/total;
selections = zeros(1,NUM_TRIALS);
for trial=1:1:NUM_TRIALS,
sel = rand(1);
lowerBound = 0;
upperBound = 0;
value = -1;
for b=1:1:COL,
lowerBound = upperBound;
upperBound = upperBound + normalizedStick(b);
if ((sel >= lowerBound) && (sel < upperBound))
value = b;
break;
end
end
end
How can I turn this into a function that takes the stick variable (which is an integer array of 2 numbers) and outputs the variable value?
  댓글 수: 1
James Tursa
James Tursa 2016년 9월 20일
What about NUM_TRIALS? Is that to be passed into the function as well? Or is it only the code inside the "trial" loop that you want in a function?

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

답변 (1개)

Walter Roberson
Walter Roberson 2016년 9월 20일
This will require that you turn the outer layer into a function as well.
Starting from R2016b you can have functions in scripts but they are not nested functions and do not have shared variable access.
You could, though, redefine your calling interface so that it passes in all values needed by the function.

카테고리

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