run script command in Matlab - 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).

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 Function fails due to : 'Error using Eval', works fine when used in Command Window

When plotting data from a .mat file, if I enter the lines from a script one-by-one, it works fine... but when I try running the script, it fails.
function Test (filename)
varname = load (filename) %or load filename
matObj = matfile(filename);
varlist = who (matObj); %or varlist = fieldnames (varname)
field1 = eval ( varlist {1} )
field2 = eval ( varlist {2} )
x1 = field1.x_values.start_value:field1.x_values.increment:field1.x_values.increment*field1.x_values.number_of_values;
x2 = field2.x_values.start_value:field2.x_values.increment:field2.x_values.increment*field2.x_values.number_of_values;
figure
hold all
%Support for yyaxis left/right not avaiable, so use plotyy
plotyy (x1, field1.y_values.values, x2, field2.y_values.values)
end
When I invoke the script (Test ('1.mat')), Matlab shows an error on the field1 = line :
Error using eval
Undefined function or variable 'Signal'.
The 'Signal' is one of the data set names in the 1.mat file.
Interestingly, when I run each line by itself in the same order from the command window, I don't get any error and the plot displays. I verified that the current path has the script and the 1.mat file, but I can't figure out why it complains about the eval when run from the script.
The issue is because your matObj is a *.mat file which contains the variable named Signal. You never load the file in your function (using load) but instead you assign a matfile object to matObj. To read a variable from this do not use eval (ever), rather you just want to use dynamic fields referencing into the matfile object.
field1 = matObj.(varlist{1});
field2 = matObj.(varlist{2});
In general though, you should probably know the name of the variables you're trying to load from the file rather than simply using the first two variables you find with who. If that's the case, just use them directly.
field1 = matObj.Signal;
The reason that your code likely worked in the command window is because at some point you probably loaded the .mat file into the command window workspace using load which would have loaded all it's contents (including Signal) into the workspace.
load('filename.mat')
Also as a bit of a nit-pick. You don't have a script you have a function (you have a function definition at the top). This has huge ramifications for diagnosing your problem. You cannot test a function by copy/pasting stuff into the command window due to the different scope of a function.

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.

Using Matlab to import another .m file

I'm quite new to Matlab. I've defined a function inside a .m file, I want to use that function in that .m file inside another .m file, and I want to run the contents of that last .m file from the command window.
How should I go about accomplishing this?
EDIT- for clarification, I have one function a inside a.m, and a script inside b.m that uses the function a inside a.m. I would like to run this script inside b.m from the command window, but am not sure how to do so. (as a side note, I can totally convert the script in b.m into a function if need be)
EDIT- right now I just need to know how to import/load a matlab file and that is it!!!
If I understand your situation correctly, you have something like this:
A file (`A.m'):
function results = A(parameters)
% some code
A file (`B.m'):
function results = B(parameters)
% some code
You want to use function A inside B, you can just call that function from inside function B:
function results = B(parameters)
% some code
otherResults = A(otherParameters)
If your situation is something like what nimrodm described, your A.m file is something like:
function results = A(paramters)
% some code
function results = C(parameters)
% code of function C
end
end
function results = D(parameters)
% code of function D
end
There is no way of directly accessing C and D from outside A. If you need to use subfunction D outside of A, just make a file D.m containing
function results = D(parameters)
% code of function D
end
And preferably, removed the same code from function A.
For a nested function C, the same can be done in some (but not all) cases, as nested functions also have access to the variables of function A. In recent versions of MATLAB (I guess R2010b or R2011a), the editor highlights variables that are shared between a function and nested functions in teal. If you don't make use of the variables of function A inside of function C, just do the same as for function D. If you do, pass these variables as parameters and/or return values and adjust the rest of your code to reflect this. Test your code and afterwards, do the same as for D.
Most likely, you will not have case C, as this is an advanced feature in MATLAB.
There is however another case, if you are not using MATLAB functions, but MATLAB scripts in different files. You can call a script (both from command line and another function or script, just by its (file) name.
contents of file E.m:
% code for script E
contents of file F.m:
% some code
E;
Using that code, you execute all commands in E from inside script F. Beware that E and F will share all their variables, so if you begin your scripts by something like clear all; close all; clc;, you cannot pass any variables from F into E (and you will lose all results from F calculated before calling E.
In most cases it is better to use functions instead of scripts, so that's also the way to solve such a situation: make everything into functions with decent parameters and return values.
edit:
After you 'changed' your question, it's quite easy.
Let's consider you have the function, I will use different names, as that is more intuitive to understand. You have the function ackermann inside the file ackermann.m which you want to call from the script bigScript.m.
The file ackermann.m contains the Ackermann-Péter function (as an example):
function result = ackermann(m,n)
if m == 0
result = n + 1;
elseif m > 0
if n == 0
result = ackermann(m-1,1);
elseif n > 0
result = ackermann(m-1,ackermann(m,n-1));
else
error('n has to be positive');
end
else
error('m has to be positive');
end
end
From inside your big script, you can call the function ackermann as follows (if you want m = 1 and n = 1):
A = ackermann(1,1)
It's that simple, no need to load anything. But you need to remember to have the function 'available in your path', the easiest way to do this, is just keep the script and function files in the same directory.
Anyhow, I sense you are a starting MATLAB user: if you don't know what a function does, just type help functionname (substituting functionname of course) into the command window. You will notice that the function load is there to load data files, not for m-files (as the m-files in your path are used automatically).
In principle, MATLAB advocates the use of one function per .m file. You can call such a function from another .m file and from the MATLAB command line.
You can define multiple functions in one .m file, but only the first (or 'outermost') function can be accessed from other .m files or the command line. The other functions are treated as 'helper' functions that may be called only inside this particular .m file.
For anyone else searching for this question, as I did, just type:
addpath('[Path name of mat file]');
This will tell Matlab how to find the function. To verify, just type:
which [function name]
If successful, it should list the path name that you just added.