read function from text file in matlab - matlab

I'm going to read some function from a Unicode text file in matlab and calculate there answer with my own variables. first i use fopen to read the text file, then what should i do to convert each line of that text file to a function? for example the func.txt contains:
(x^2)-3y
sin(x+z)+(y^6)
and i need to write an m.file which read func.txt and process that like this:
function func1[x,y] = (x^2)-3y
function func2[x,y,z] = sin(x+z)+(y^6)

Preamble: if your final aim is to use those functions in matlab (i.e. evaluate them for some values of x,y,...), I would rather suggest the following approach that looks more robust to me.
In principle, in fact, you don't need to manipulate the file funct.txt to evaluate the functions defined therein.
First problem: each line of your file funct.txt must define an inline function.
Say that the first function (i.e., the first line) of the file funct.txt has been copied into a string str,
str = '(x^2)-3y',
you can obtain a function from it using the command inline:
f1 = inline(str,'x','y');
which gives to you (matlab output)
f1 =
Inline function:
f1(x,y) = (x^2)-3y.
Now you can use f1 just calling it as f1(x,y), for whatever values x,y.
Second problem: you have to parse your file funct.txt to obtain the strings str containing the definitions of your functions. That's easier, you may want to consider the function fgets.
Third problem: the functions in funct.txt may depend on 2,3 (or more?) independent variables. As far as I know there is no easy way to parse the string to discover it. Thus, you may want to define each inline function as depending on all your independent variables, i.e.
f1 = inline('(x^2)-3y','x','y','z');
the variable z will play no active role, by the way. Nonetheless, you need to specify a third dummy parameter when you call f1.

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

How to apply MATLAB addpath to non static string?

dir1 = '/tmp1';
dir2 = '/tmp2'
If we do the following
addpath [dir1 dir2];
MATLAB takes '[dir1 dir2]' as the path name to add. We can do the following
eval(sprintf(...
'addpath %s;', ...
[dir1 dir2]));
I was wondering if there is any better way. Thank you,
A very simple way to achieve what you want is to call:
addpath(fullfile(dir1,dir2));
Fullfile will take care of adjusting the string to be a proper folder name (under both Windows and Unix) as in:
fullfile('foo','bar') % returns foo/bar
fullfile('foo/','bar') % returns foo/bar
To add files recursively just do:
pathsToAdd = genpath(fullfile(dir1,dir2));
addpath(pathsToAdd);
The general issue that you are having is that MATLAB has two ways of calling commands. The first does not use an explicit function call function() but rather just multiple inputs on the command line separated by a space:
addpath directory1 directory2
As you know this will add both directory1 and directory2 to the path.
What is happening here is that MATLAB converts all of the inputs to strings implicitly and passes them to the addpath function. The explicit equivalent is
addpath('directory1', 'directory2')
As you can see, internally MATLAB calls addpath like a normal function with input parameters, and as such you can pass it variables rather than string literals:
dir1 = 'directory1';
dir2 = 'directory2';
addpath(dir1, dir2);
This is why you are seeing an issue with:
addpath [dir1 dir2]
Because, as written, [dir1 dir2] is convert to a string (implicitly) since it was passed using the function parameter1 parameter2 syntax rather than the explicit function syntax.
Also, be careful because [dir1, dir2] doesn't do what you think it does. What it actually does it appends the strings dir1 and dir2 and would result in:
[dir1, dir2]
/tmp1/tmp2
If that is what you expect, then use fullfile rather than basic horizontal concatenation to ensure you have the proper file separators, etc.
addpath(fullfile(dir1, dir2));
You will actually see the implicit syntax in many MATLAB functions that accept only strings as input parameters. It is important to know, though, that you can always use the explicit function call function() instead to pass input strings which may be stored in variables.

Get output variable name from load function load in Matlab

I want to load an ASCII-file using this syntax:
load('10-May-data.dat')
The returned output variable name should be X10_May_data.
Is there a way to get the variable name in Matlab? If I want to use regular expression to do the translation, how can I do it? For example, put an X before any underscores or digits in the filename and replace any other non-alphabetic characters with underscores.
The who function returns the names of variables in matlab. It also has a built-in regexp for selecting certain items:
X10_May_data = [1 2 3];
save X10_May_data.mat X10_May_data
clear
load X10_May_data.mat
w = who('-regexp','X*')
w =
'X10_May_data'
You can then operate on w{1} to do any substitutions you want. For example, use the strrep function for simple modifications of a string:
newvar = strrep(w{1},'May','latest')
newvar =
X10_latest_data
For more complex modifications, use regexp or regexprep. When you have the new name, you can assign it with eval:
eval([newvar '=' w{1}]) % like typing "X10_latest_data = X10_May_data"
X10_latest_data =
1 2 3
[edit] PS I agree with the comments that eval is usually a bad idea; but sometimes you just need to get something done :) For alternative approaches, see the matlab page on the topic.

save svm models to file matlab

I have 31 models an I want to save each one in a specific file
this is my matlab function
formatspec='model%d'
for k = 1:length(libsvmFiles)
baseFileName = libsvmFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
[labels train]=libsvmread(fullFileName);
model=svmtrain(labels,train, '-t 2 -h 0');
file=sprintf(formatspec,k);
save file model;
but the problem is only the first file is saved and its name is 'file' tha's mean the value of the variable file is not evaluated
how can I solve this problem ?
As many Matlab functions, save can be used in function form (save(...)) or in command form (save ...). In the command form that you use, all the arguments are interpreted as strings. That means
save file model
is equivalent to
save('file', 'model')
For the second argument that is correct, because you want to refer to the variable with the name "model". For the first argument it is wrong, because you want to refer to the file name contained in the variable file. The correct syntax to use is therefore
save(file, 'model')
You're missing the parens for the save function. The model variable also needs to be listed as a string since you need to tell the save function the name of the variable, not the variable itself. See Matlab's documentation.
save(file, 'model');
Additionally you don't have an end to your for loop shown, which normally would just throw an error -- however later code might cause this loop to instead only run once. Otherwise you should check your libsvmFiles variable as it might be only length 1 or not be an array.

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.