undefined variable or function - matlab

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.

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

Creating a new file in the script folder using fopen

I'm using MATLAB R2017a and I would like to create a new binary file within the folder the script is running from.
I am running matlab as administrator since otherwise it has no permissions to create a file. The following returns a legal fileID:
fileID = fopen('mat.bin','w');
but the file is created in c:\windows\system32.
I then tried the following to create the file within the folder I have the script in:
filePath=fullfile(mfilename('fullpath'), 'mat.bin');
fileID = fopen(filePath,'w');
but I'm getting an invalid fileId (equals to -1).
the variable filePath is equal in runtime to
'D:\Dropbox\Studies\CurrentSemester\ImageProcessing\Matlab
Exercies\Chapter1\Ex4\mat.bin'
which seems valid to me.
I'd appreciate help figuring out what to do
The problem is that mfilename returns the path including the file name (without the extension). From the documentation,
p = mfilename('fullpath') returns the full path and name of the file in which the call occurs, not including the filename extension.
To keep the path to the folder only, use fileparts, whose first output is precisely that. So, in your code, you should use
filePath = fullfile(fileparts(mfilename('fullpath')), 'mat.bin');

Matlab: set current working directory as top priority in path

In one of my projects, I have a Matlab function called eom.m. When I try to call it, I get errors. I have realised this is because Matlab calls a simulink file, eom.slx, instead, which is in one of the toolboxes.
I would prefer not to rename the function, so I was wondering how I could change the order in the Matlab path so that the folder I call Matlab from always has top priority. That is to say how I can ensure that the files in my current working directory are always those that are called in fact.
Thank you for the help!
You can do it programmatically using addpath with the '-begin' option.
You can use command syntax:
addpath c:/path/you/want -begin
Enclose with quotes if the path contains spaces:
addpath 'c:/path /you/ want' -begin
Alternatively, you can use function syntax:
addpath('c:/path/you/want', '-begin')
This allows having the path stored in a variable:
p = 'c:/path/you/want';
addpath(p, '-begin')

run script command in Matlab

I am running a script in another directory.
Assume I have the following code:
arr = [10;20;30];
run(script); % script= path to the script file + scriptfile.mat ..
x = arr(2);
It gave me the following error:
Undefined function 'arr' for input arguments of type 'double'.
After debugging the code, I found that run(script) .. run the script and then clear all variables .. such as arr.
Is there any way to make run command doesn't clear all variables..
Edit: the following is the original code..
xValues =[2;4;6];
yValues =[10;15;20;30;40];
for var1 =1:size(xValues,1)
results =[];
for var2 =1: size(yValues,1)
run(strcat('C:\Users\as\Desktop\study',num2str(xValues(var1)),'folder\',num2str(yValues(var2)),'folder\file1.m'));
results(var2,1) = yValues(var2);
end
end
Thanks,
Here is an example, erase clear command in your script file:
testing.m
arr = [10;20;30];
run('ScriptFile.m')
x = arr(2);
ScriptFile.m
disp('Hello World');
Command Window
Hello World
After the implementation x holds number 20.
It is clear all inside your script doing the mess I believe.
As for how to avoid it:
Simply remove it. This is generally the easiest and best solution.
Write file to the disk, run script, load from disk. You need a hardcoded file name.
Create "data_holding_function" that has persistent cell array, you load your data there and then restore it after script. You can make the function perform both loading (when you have some input) and unloading (when you don't).

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

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."