arguments of a function in matlab - matlab

I am writing a function with two arguments and I want the second argument to be processed as a string. The following code encounters an error
function Derivative = derive ( Matrix9x1 , string Variable )
end
How can I tell it to matlab?
I mean even if the user inputs 1 as the second argument it should be processed as an string
and the user should be able to enter for example omega

The second argument to your function will only be processed 'as a string' if it 'is a string', that is if you enclose it in single quotation marks. If you want to pass a number to a function and turn it into a string for further operations, use the function num2str. If you want to write a function which takes different actions depending on the type of the second argument you're going to have to test that type when the function is called; you might want to look at the functions ischar, isstrprop, isnumeric, and their relations.
Oh, and don't forget that a Matlab 'string' is really an array of characters which are just a convenience 'type' for integers-representing-characters.

Matlab functions are unlike programming language functions. Not that your example in these programming languages will not work either. Passing an integer to a function that expects a string, will give you compilation errors.
The best alternative in Matlab that I can think of will be to check or convert the second input variable inside the function. Maybe this can help you: http://www.mathworks.nl/help/techdoc/ref/typecast.html

Related

"Not enough input arguments" error using add_line()

I'm trying to use add_line() to organize a link with the 'autorouting' parameter.
Here is my code :
add_line(sprintf('%s',diagrammeName), [pos_array_out{pos_out};pos_array_in{pos_in}], 'autorouting','on');
where pos_array_out is a cell of Output position and pos_array_in is a cell of Input position.
And pos_in and pos_out are indices of cell.
But it returns an error :
Not enough input arguments
Why do I get this error?
add_line() has three mandatory arguments when using name-value pairs: sys, out, and in, and optional name-value pairs. Breaking down your input:
add_line(sprintf('%s',diagrammeName),...
[pos_array_out{pos_out};pos_array_in{pos_in}],...
'autorouting','on'...
);
Directly tells you what the problem is. You have two input variables: 1) sprintf('%s',diagrammeName), 2) [pos_array_out{pos_out};pos_array_in{pos_in}], and the name-value pair ('autorouting','on'). So basically you fed it two of the three mandatory parameters, hence you get the error.
I suspect, due to the way you use your variable names, you should do
add_line(sprintf('%s',diagrammeName),...
pos_array_out{pos_out},...
pos_array_in{pos_in},...
'autorouting','on'...
);
i.e. split the out and in variables as suggested in the documentation.
The other type of input add_line() accepts is h = add_line(sys,points), in which case you have two positional arguments, like you do here, but cannot use name-value pairs apparently. The reason for this is that the former syntax tells you where the line starts and where it ends, and name-value pairs then control what the line looks like, i.e. where the line actually passes (moving around objects). Using sys, points is like doing plot(x,y), it draws a line between pre-specified points. Using a name-value pair to control the shape is then moot, since you already implicitly provide the shape with the points.
Doing [a;b] creates an array, which is a single variable, hence the error.

kdb/q question: How do I interpret this groupby in my functional selection?

I am new to kdb/q and am trying to figure out what this particular query means. The code is using functional select, which I am not overly comfortable with.
?[output;();b;a];
where output is some table which has columns size time symbol
the groupby filter dictionary b is defined as follows
key | value
---------------
ts | ("+";00:05:00v;("k){x*y div x:$[16h=abs[#x];"j"$x;x]}";00:05:00v;("%:";`time)))
sym | ("k){x'y}";"{`$(,/)("/" vs string x)}";`symbol)
For the sake of completeness, dictionary a is defined as
volume ("sum";`size)
In effect, the functional select seems to be bucketing the data into 5 minute buckets and doing some parsing in symbol. What baffles me is how to read the groupby dictionary. Especially the k)" part and the entire thing being in quotes. Can someone help me go through this or point me to resources that can help me understand? Any input will be appreciated.
The aggregation part of the function form takes a dictionary, the key being the output key column names and the values being parse tree functions.
A parse tree is an expression that is not immediately evaluated. The first argument as a function and subsequent elements are its arguments. The inner-most brackets are evaluated first and then it moves up the heirarchy, evaluating each one in turn. More detailed information can be found here and in the whitepaper linked on that page
You can use the function parse with a string argument to get the parse tree of a function. For example, the parse tree for 1+2+3 is (+;1;(+;2;3)):
q)parse "1+2+3"
+
1
(+;2;3)
The inner-most bracket (+;2;3) is evaluated first resulting in 5, before the result is propogated up to the outmost parse tree function (+;1;5) giving 6
The groupby part of the clause will evaluate one or more parse tree functions and then will collect together records with the same output from the grouping function.
Making the function a bit clearer to read:
(+;00:05:00v;({x*y div x:$[16h=abs[#x];"j"$x;x]}";00:05:00v;(%:;`time)))
Looking at the inner most bracket (%:;`time), it returns the result of %: applied on the time column. We can see that %: is k for the function ltime
q)ltime
%:
Moving up a level, the next function evaluated is the lambda function {x*y div x:$[16h=abs[#x];"j"$x;x]} with arguments 00:05:00v and the result of our previous evaluated function. The lambda rounds it down the the nearest 5 minute interval
({x*y div x:$[16h=abs[#x];"j"$x;x]};00:05:00v;(%:;`time))
Moving up once more to the whole expression it is equivalent to 00:05:00v + {x*y div x:$[16h=abs[#x];"j"$x;x]};00:05:00v;(%:;`time)), with 00:05:00 being added onto each result from the previous evaluation.
So essentially it first returns the local time of the timestamp, then
For the symbol aggregation
("k""{x'y}";{`$(,/)("/" vs string x)};`symbol)
The inner function {`$(,/)("/" vs string x)} strings a symbol, splits it at "/" character and then joins it back together, effectively removing the slash
The "k" is a function that evaluates the string using the k interpreter.
"k""{x'y}"" returns a function which itself takes a function x and argument y and modifies the function to use the each-both adverb '. This makes it so that the function x is applied on each symbol individually as opposed to the column as a whole.
This could be implemented in q instead of k like so:
({x#'y};{`$(,/)("/" vs string x)};`symbol)
The function {x#'y} takes the function argument {`$(,/)("/" vs string x)} and the symbol column as before, but we have to use # with the each-both adverb in q to apply the function on the arguments.
The aggregation function will then be applied to each group. In your case the function is a simple parse tree, which will return the sum of the size columns in each group, with the output column called volume
a:enlist[`volume]!enlist (sum;`size)

MATLAB function output ans unwanted

I have a function
function [ obsTime, obsWDIR, obsWSPD, obsSWH, obsMWD ] = readObsC(obsFile, endTime)
that when I run it, it gives an output of a huge array ans, which is the same array as obsTime. But obsTime, obsWDIR, obsWSPD, etc. don't display. Not a single line of code is supposed to display ans.
When I'm in debugging mode, I run the code and stop it at the very last line, and it doesn't give an output ans. Only when I hit 'step' twice and the function ends, does the ans output appear.
Everything in the function has semicolons.
Why does ans appear? Where are my other outputs?
In your function definition, you name the formal input and output arguments. That determines the name which these arguments will use within the function.
The function has its own environment, and variable names inside the function are completely independent of variable names outside the function, unless you use global or evalin('caller').
You have to provide actual input and output arguments at the time of the call, which determines how the code outside the function refers to those same arguments. There is no automatic passing of arguments simply because the names match! The only automatic thing is that if you don't specify the actual output arguments, the first actual output argument will be ans and the rest are discarded.
You could have figured this out if you simply read the MATLAB documentation for ans:
The MATLABĀ® software creates the ans variable automatically when you specify no output argument.
The function declaration specifies the return values, but when you call it, you don't specify anywhere for the output to go. When you call something on the command line, the output is always defaulted to ans unless you assign a variable to the output of the function when you call it.
I defined a simple function called myfunc as:
function [one,two,three,four] = myfunc(value1,value2)
Ex, using workspace variables (denoted ws_) to capture function output:
>> [ws_one,ws_two,ws_three,ws_four] = myfunc(1,2)
prints:
ws_one =
1
ws_two =
2
ws_three =
1
ws_four =
2

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.

Issue on writing a function with string as the argument

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.