function inside main program

조회 수: 5 (최근 30일)
Chrys
Chrys 2020년 5월 25일
답변: Image Analyst 2020년 5월 27일
i have to import excel data for the looping calculation in the function, for example:
table = dataset('xlsfile','xyz.xlsx');
X = table.x;
function program(i)
a = 1;
for k = 1:n
a = a * X(k)*i;
end
but when i input
i = 0.5;
program(i)
in the command window (the input have to be exactly like that) it says error. what should i change so that the program can work with the input i mentioned before. please help me thank you.

답변 (2개)

Geoff Hayes
Geoff Hayes 2020년 5월 25일
Chrys - in your function, you are referencing the variable X but it isn't been defined either within that function or passed in to this function. (Presumably the error is something like 'X' is undefined variable or function. You indicate that the input has to be exactly like the above (so just the one input parameter) so if you can't pass X into the function, then your function needs to read this data from file.
function program(i)
table = dataset('xlsfile','xyz.xlsx');
X = table.x;
a = 1;
for k = 1:n
a = a * X(k)*i;
end
Note that you while your code updates a it doesn't do anything with it once the loop completes. Should a be an output parameter?
  댓글 수: 2
Chrys
Chrys 2020년 5월 27일
a is not directly an output but it does connected to the output. Thank you so much for your answer it helps alot
Chrys
Chrys 2020년 5월 27일
a is not directly an output but it does connected to the output. Thank you so much for your answer it helps alot

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


Image Analyst
Image Analyst 2020년 5월 27일
What is this:
table = dataset('xlsfile','xyz.xlsx');
X = table.x;
function program(i)
a = 1;
for k = 1:n
a = a * X(k)*i;
end
Is that all in one single m-file? If so, it's a script followed by a function. And the function program would need to have an extra "end" at the end of it. Those are the rules for a function inside a script.
Also, that is that m-file called? I don't think you can call it program.m because program() is a nested function inside the m-file. You could name it program.m if those first two lines weren't there. Otherwise you'll need to pick a different name, like testProgram.m or something.
But since you seem to want to also call program() from the command line, you'd be best off making an m-file with only these lines of code in them:
function a = program(factorToMultiplyBy)
a = 1;
for k = 1 : n
a = a * X(k) * factorToMultiplyBy;
end

카테고리

Help CenterFile Exchange에서 R Language에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by