Help with funtion to return True or False - Function definitions are not permitted in this context

25 Ansichten (letzte 30 Tage)
Hello
I have written a function for a main program and this simple function should return true (1) or false (0) depending on a random value generated.
function [outs] = is_ph_emitted()
QY = 0.8;
randvals = rand(1) % Random number
if (randvals <QY)
% Photon is emitted and this function returns logical true
outs = true;
else
% Photon not emitted
outs = false;
end
end
I've saved the file as the same name as the function (is_ph_emitted.m). This function is behaving strangely because I can run in the command window, although it always returns false. When I try to debug it, it won't let me enter the function and returns "The selected section cannot be evaluated because it contains an invalid statement" And in the command window -
function [outs] = is_ph_emitted() ↑ Error: Function definitions are not permitted in this context.
Any help would be much appreciated! Thanks
  2 Kommentare
Henry Giddens
Henry Giddens am 5 Sep. 2016
Are you calling the function correctly? When you call the function from the command line (or another script/function), don't include the word 'function'
outs = is_ph_emitted
rather than
function [outs] = is_ph_emitted()
Jan
Jan am 22 Sep. 2016
Bearbeitet: Jan am 22 Sep. 2016
Please post what you exactly do, when you "try to debug it". Most likely this detail contains the problem. The term "The selected section..." does not sound like the standard method to use the debugger. Actually there should not be a "selected section".

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 22 Sep. 2016
Bearbeitet: Jan am 22 Sep. 2016
You see in the workspace browser that is_ph_emitted is a variable also. Please check if there are not several different variables or function definitions with this name:
which is_ph_emitted -all
By the way: Using globals will increase the confusion level without any benefits. Therefore they are considered a bad programming style, because they impede the debugging.
  1 Kommentar
Maja Gajic
Maja Gajic am 23 Sep. 2016
Hello. That's it. I was accidentally using it as a variable in the main function. Thanks for your help!
I thought global variables are useful because I have some material parameters I want to pass into many functions but I see how they can make things harder. So the alternative would be to pass values in and out of functions? That also seems like a lot to keep track of.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by