function inside main program
4 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Geoff Hayes
on 25 May 2020
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
on 27 May 2020
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 Comments
See Also
Categories
Find more on R Language in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!