Issue on writing a function with string as the argument - matlab

I need to write a function whose input argument should be file name, and the function will perform certain operation on the opened file. Here is the sample function I wrote,
function readFile = loadOneColumnFile(fileName)
fid1 = fopen(fileName);
readFile = 0;
fclose(fid1);
But when I invoke this function in the command console as follows,
>> testValue = loadOneColumnCSV('/usr1/test.csv');
The Matlab returns the following error message
??? Undefined function or method 'loadOneColumnFile' for input arguments of type 'char'.
Looks like that the definition of function is not correct. How to fix it? Thanks.

MATLAB treats a string as an array of characters (like C++, except the strings are not null-terminated in MATLAB).
Despite the error message, I don't think there is any problem with the string passing. The problem is MATLAB cannot find your function. So:
The file containing the function must have same name as the function (in your case save the function in a file named loadOneColumnFile.m)
The loadOneColumnFile.m must be placed in the working (current) directory so MATLAB could find it.
The name of the function is not consistent in your question. Make sure you have used only one of the loadOneColumnFile or loadOneColumnCSV for naming the function and filename.

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

Puzzling error with script run in function

I'm experiencing a puzzling error in Matlab R2012b. It seems that variable names that are also data types exhibit strange behavior. Please see this small example:
function [] = test1()
dataset = 1;
if dataset ~= 0
disp hello
end
end
A call to test1() produces output hello, as expected.
Now, rather than set the value of dataset in my function, I run a script instead.
function [] = test2()
myscript;
if dataset ~= 0
disp hello
end
end
where myscript.m has one line:
dataset=1;
Now, when I call test2() I get this error:
Undefined function 'ne' for input arguments of type 'dataset'.
Error in test2 (line 4)
if dataset ~= 0
(Forgive the variable named dataset - I know that it is also the name of a data type, and it came in the code I was running.) So it seems as if in test2, Matlab creates an empty dataset object rather than using the variable named dataset. Furthermore, this behavior only appears when I set the value in a script rather than in the function body. Even more weird, is that I can do:
>> dbstop in test2 at 4 % line of if statement
>> test2()
K>> dataset
dataset =
1.00
K>> dataset ~= 0
ans =
1
K>> if dataset ~= 0, disp hello; end
hello
K>> dbcont
and I get the same error! The error is not displayed in debugging mode but it is in normal execution.
Can anyone reproduce this? What is going on here?
The MATLAB online help has some pages dealing with this issue; Variables Names and Loading Variables within a Function seem to be the most relevant.
There is no explicit page that discusses how MATLAB resolves names at compilation time, but there is one little tidbit at the bottom of the Variables Names page: "In some cases, load or eval add variables that have the same names as functions. Unless these variables are in the function workspace before the call to load or eval, the MATLAB parser interprets the variable names as function names."
In other words, if the parser finds an explicit assignment to a variable whose name is the same as another existent object, the local definition takes precedence.
In your test2(), there is no explicit assignment to a variable dataset; therefore, when the file is compiled, the parser interprets dataset to be a class constructor (since the parser will not run or inline myscript into the function).
Then at run-time, even though a variable named dataset has been poofed1 into the function's workspace, the interpreted code that is running still has the dataset symbol in the if-statement associated with the class constructor.
If you need to, you can still use the dataset variable name and load from an external file, but it should be done with an explicit assignment via a function call. For example:
dataset = initialize();
Now the parser will notice that dataset is some arbitrary output of the function initialize and all will be well. In fact, you can have even have initialize return a dataset constructor to the dataset variable if you wanted.
1 When variables are defined without explicit assignment, MATLAB people (at least on some of their blogs I've read) called this 'poofing'. Using load without any output arguments, using eval, and simply running scripts (not functions) can all poof variables into the workspace. This can work fine as long as the variable names do not conflict with other in-use symbols at compile time.

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.

read function from text file in 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.