function inside main program
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
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?
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 R Language 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!