function inside main program

1 view (last 30 days)
Chrys
Chrys on 25 May 2020
Answered: Image Analyst on 27 May 2020
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.

Answers (2)

Geoff Hayes
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?
  2 Comments
Chrys
Chrys on 27 May 2020
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 on 27 May 2020
a is not directly an output but it does connected to the output. Thank you so much for your answer it helps alot

Sign in to comment.


Image Analyst
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

Tags

Community Treasure Hunt

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

Start Hunting!