Is it possible to check if a given Matlab script is run by itself or called by another script? - matlab

I have a Matlab script A that can either be run by itself or be called by another script. I want to enter an if statement in script A that checks if the script is run by itself or called by another script. How can I check this?

You should check out dbstack.
dbstack displays the line numbers and file names of the function calls that led to the current breakpoint, listed in the order in which they were executed. The display lists the line number of the most recently executed function call (at which the current breakpoint occurred) first, followed by its calling function, which is followed by its calling function, and so on.
And:
In addition to using dbstack while debugging, you can also use dbstack within a MATLAB code file outside the context of debugging. In this case, to get and analyze information about the current file stack. For example, to get the name of the calling file, use dbstack with an output argument within the file being called. For example:
st=dbstack;
The following is stolen from the iscaller function posted on the File Exchange.
function valOut=iscaller(varargin)
stack=dbstack;
%stack(1).name is this function
%stack(2).name is the called function
%stack(3).name is the caller function
if length(stack)>=3
callerFunction=stack(3).name;
else
callerFunction='';
end
if nargin==0
valOut=callerFunction;
elseif iscellstr(varargin)
valOut=ismember(callerFunction,varargin);
else
error('All input arguments must be a string.')
end
end
Credit for this approach goes to Eduard van der Zwan.

You can use the function dbstack - Function call stack.
Let's add this to the beginning of your script file, call it 'dbstack_test.m':
% beginning of script file
callstack = dbstack('-completenames');
if( isstruct( callstack ) && numel( callstack ) >= 1 )
callstack_mostrecent = callstack(end); % first function call is last
current_file = mfilename('fullpath'); % get name of current script file
current_file = [current_file '.m']; % add filename extension '.m'
if( strcmp( callstack_mostrecent.file, current_file ) )
display('Called from itself');
else
display( ['Called from somewhere else: ' callstack_mostrecent.file ] );
end
else
warning 'No function call stack available';
end
Add a second script called 'dbstack_caller_test' to call your script:
run dbstack_test
Now when you run dbstack_test from the console or click the green triangle in your MATLAB editor:
>> dbstack_test
Called from itself
When you call it running from dbstack_caller_test
>> dbstack_caller_test
Called from somewhere else: /home/matthias/MATLAB/dbstack_caller_test.m
When you call it within MATLAB's editor using "run current section" (Ctrl+Return) you get
Warning: No function call stack available
Of course you can modify the code dependent on which level you are required to use from the call stack.
As already mentioned in the documentation: "In addition to using dbstack while debugging, you can also use dbstack within a MATLAB code file outside the context of debugging."

Related

MATLAB is saying th function is undefined

I am writing a script to access a function that has been written in another script.
When I run the second script the error is that the function is undefined.
I have been working backwards and am currently trying to get the function to work in the command window.
The function file has appeared in the current folder window. When it is highlighted all functions and parameters are displayed in the window below (displays the file name on top then the file contents).
I am still getting a function is undefined when I copy and paste the functions call from the script into the command window.
I tried rebuilding the functions individually in separate scripts, but I am still receiving an error message.
I have made sure the are in the same folder, and are spelled exactly the same, what am I doing wrong?
'''
%file name Lab_5_functions.m
function[vel] = velocity (g,m,co_d,t)
vel= ((g*m)/co_d)^(1/2)*tanh(((g*co_d)/m)^(1/2)*t);
end
function [dvel]= dvelocity (g,m,co_d,t)
dvel=(((.5*(g*m)/co_d)^(1/2)*tanh(((g*co_d)/m).^(1/2)*t_sec))-(((g*t)/(2*m))*(sech(((g*co_d)./m).^(1/2)*t))));
end
'''
v=velocity(1,2,3,4)
%error message below:
Undefined function or variable 'velocity'.
'''
Thanks
-MK
Matlab is searching for functions using filenames. So you define a single public function myfunc in a file myfunc.m.
You can define additional functions in that file, but they will not be accessible outside that .m file.
MATLAB looks for filenames to find the functions and expects the first line of that file to be a function definition.
For example: myfunc.m
function output = myfunc(input)
If you do want many functions in one file (like a module/library), I have used a work-around before: write all your functions in the file, then include an if-else block to call the correct function. Multiple arguments can be parsed with some simple checks (see nargin function). It is a less elegant solution; I only use it if I have many simple functions and it would be plain annoying to have heaps of .m files.
Here is a simple example:
Call the file: myfunc.m
function output = myfunc(fn, arg1, arg2, ...)
function out = func1(arg1, arg2, ...)
out = 0
if strcmp(fn, 'func1')
if nargin == 2
output = func1(arg1)
end
elseif strcmp(fn, 'func2')
...
end

Matlab statement is not inside any function error

This is a simple Matlab code that I'm trying to execute.
function result = scale(img, value)
result = value .* img;
end
dolphin = imread('dolphin.png')
imshow(scale(dolphin, 1.5));
The error says:
Error: File: scale.m Line: 5 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "scale".)
What am I doing wrong here?
scale.m is a function M-file because it begins with the keyword function. The part up to end is the definition of the function. When you call scale at the MATLAB command line, it executes the code in the function. The stuff that comes after end is not part of the function, and hence cannot be executed.
If you intended to write a script with a private function scale that you want to use only within this script, then put the lines of code that read and display dolphin at the top of the file. The private functions should come after the script part. This syntax is supported since MATLAB R2016b.
Otherwise, move the dolphin code to a different M-file, which would be a simple script M-file without any function definitions. This script can then use scale, which would call the function in the file scale.m.
A third alternative, keeping all code in the same file, is to not use a script at all, and put the script code inside a function:
function f % just a random name
dolphin = imread('dolphin.png')
imshow(scale(dolphin, 1.5));
end
function result = scale(img, value)
result = value .* img;
end
(The function name doesn't need to match the file name, although the MATLAB editor will warn you if these names don't match.)

Matlab / Octave - trouble getting started with functions, is there a function main equivalent?

I'm trying to get started with Matlab / Octave and having a difficult time figuring how to organize a program into functions. Currently I'm trying to write a simple program that adds two numbers together and displays the result, with the adding being done by a function. I would have figured this would have worked:
% test.m
close all;
clear all;
num1 = 2;
num2 = 2;
result = myAdd(num1, num2);
disp(result); % this should display 4 ??
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function retval = myAdd(var1, var2)
retval = var1 + var2;
end
Running the above with Octave 4.0.0, I get the following errors:
error: 'myAdd' undefined near line 7 column 10
error: called from
test at line 7 column 8
I have tried also putting the function first and the test part second, and also putting the function in a separate file and having a main.m file in the same directory call the myAdd function, all result in errors.
So here are my questions:
-Does Matlab / Octave have a main equivalent ??
-How does the interpreter know where to start? Does it automatically go to the first line in the program, or is there a certain function name you can use to make it start with that function as function main() is in C/C++ ??
-In a Python program of significant size, my usual practice is to organize things as follows:
# some_python_program.py
import abc
import xyz
###################################################################################################
def main():
# stuff to get program started here
# end main
###################################################################################################
def function1():
# specific function here
# end function
###################################################################################################
def function2():
# specific function here
# end function
###################################################################################################
if __name__ == "__main__":
main()
Is there a way to do the equivalent in Matlab/Octave ??
If somebody could provide some direction as to a main equivalent and/or how to organize functions in Matlab/Octave please advise, thanks.
Matlab/Octave can be a bit confusing in this way if you're coming from a language like python. In order to define a function (without using anonymous functions), you need to create a separate file with the name of that function, which can then be called using the command line.
For example, you would like to create a function called myadd. You should create a file named myadd.m whose contents will be:
function out = myadd(a,b)
out = a+b;
end
Then, as long as your file is on your path (save it to your MATLAB folder or put it in your current working directory), you can call it from the Command Window as follows:
>> myadd(5,6)
ans =
11
Only one function will be made publicly available per file (the one whose name matches the file name). However, you can still define multiple functions per file if you plan to use only that function. For example, if you have a file named foo.m, you can do the following:
function out = foo(a,b)
out = fun(a,b);
end
function out = fun(a,b)
out = a * b;
end
This will allow you to call foo(5,6) from the Command Window, but fun(5,6) will result in an error: Undefined function or variable 'fun'.
Read more about local functions and nested functions.
Hope this is helpful!

undefined variable or function

I have created a function in MATLAB & have saved it as an m file. When I run my function, it's fine. However using the Windows 7 scheduler it goes to run my function and gives the error message 'Undefined variable 'myMethod' or function 'myMethod.m'.
When I run the which('myMethod.m') it returns the correct folder so not sure what this error message is about?
The pwd method returns the correct address of where my function is too, C:\SomeFolder\MATLAB\Me
Probably its simply not finding the function because it is not on the path.
Assuming you can run builtin functions via the scheduler, try something like this:
p = path
save p
% save c:\ p
In case you cannot even find the saved file, use the last line instead.
Match the path with your files location and presumably the path does not contain the folder which holds your file.

Running a matlab program with arguments

I have a matlab file that takes in a file. I would like to run that program in the matlab shell, such as prog. I need to implement it so that it takes a number of arguments, such as "prog filename.txt 1 2 which would mean that i can use filename.txt and 1 2 as variables in my program.
Thank you!
In order to make a script accept arguments from the command line, you must first turn it into a function that will get the arguments you want, i.e if your script is named prog.m, put as the first line
function []=prog(arg1, arg2)
and add an end at the end (assuming that the file has only one function). It's very important that you call the function the same name as the file.
The next thing is that you need to make sure that the script file is located at the same place from where you call the script, or it's located at the Matlab working path, otherwise it'll not be able to recognize your script.
Finally, to execute the script you use
matlab -r "prog arg1 arg2"
which is equivalent to calling
prog(arg1,arg2)
from inside Matlab.
*- tested in Windows and Linux environments
Once your function is written in a separate file, as discussed by the other answer you can call it with a slightly more complicated setup to make it easier to catch errors etc.
There is useful advice in this thread about ensuring that Matlab doesn't launch the graphical interface and quits after finishing the script, and reports the error nicely if there is one.
For example:
matlab -nodisplay -nosplash -r "try, prog(1, 'file.txt'), catch me, fprintf('%s / %s\n',me.identifier,me.message), exit(1), end, exit(0)"
The script given to Matlab would read as follows if line spaces were added:
% Try running the script
try
prog(1, 'file.txt')
catch me
% On error, print error message and exit with failure
fprintf('%s / %s\n',me.identifier,me.message)
exit(1)
end
% Else, exit with success
exit(0)