Ignoring an output from a Matlab function [duplicate] - function

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to elegantly ignore some return values of a MATLAB function?
I have a Matlab function with two outputs. Sometimes I use both outputs.
function [output1 output2] = myFunction(input)
[a b] = myFunction(input);
Other times I only need output1 and don't want to waste memory assigning output2
a = myFunction(input);
However, I can't figure out a simple way to give the reverse scenario (only need output2 and don't want to waste memory assigning output1). I thought it would be something like
[~ b] = myFunction(input)
but that doesn't seem to work. Anybody have suggestions for a quick solution? Thanks for your help!

It's [~, b], not [~ b]. The comma is missing.

the object will be created inside myFunction either way, unless your input has a way to prevent the creation. If you can prevent the creation internally, you can modify myFunction to return a cell array or other structure, from which you can decide which elements to keep. If your concern is that [dontwant b] is wasting matlab memory by holding dontwant, then you might want to delete dontwant from your workspace by calling
clear dontwant;

Related

Should I define a new function for making a matrix Hermitian?

Let X be a square matrix. We want to force it to be Hermitian, that is: self-conjugate-transpose. X = X^H = conj(X^T). To do this in Python with numpy is easy:
X = 0.5*(X + np.conj(X.T))
I haven't found in NumPy a single function that does it in a single experssion f(x).
The question is should I define a new function to do it? E.g.
def make_hermitian(X):
return 0.5*(X + np.conj(X.T))
(one can come up with short name, e.g. "make_h" or "herm" or "selfconj").
Pros: more readable code, one operation in shorter form. If one uses shorter name it saves writing when repeated many times, and makes modification in this operation far more easy and comfortable (need to change only in place).
Cons: replaces a very short and straight-forward expression which is self-evident.
What is more appropriate way of programming: define a new function or just write the explicit expression repeatedly?
I would say it depends on how many times you need to reuse that function.
If it's more than twice, then definitely make a function. If it's only once or twice, I would say it's up to you. If you choose to go with no function, add a short comment specifying what such piece of code is supposed to do.
My preference in any case would be defining a function with a meaningful name, because if anyone else is going to / supposed to read the code, they may not know or remember how to achieve a Hermitian matrix, and hence the math alone ain't going to be sufficient.
On the other hand, a meaningful function name will tell them clearly what it's going on, and they can google after what a Hermitian matrix is.

Information about a function's input parameters from within another function [duplicate]

This question already has answers here:
How do I retrieve the names of function parameters in matlab?
(6 answers)
Closed 8 years ago.
I'm trying to write a general function in MATLAB that takes a function handle as one argument and a path as a second, with optional filters defining which files in the specified folder should be used. The idea is that the inputted function is then applied to all the matching files. However, I want to make sure that there's no uncontrolled crashing of this function, so I'd like to be able to check if the inputted function even takes files as input arguments.
So to sum up, I'd like to know if there's a way to find out if certain input is compatible with a certain function, with only the function handle to go on. I know MATLAB is very loose in these things but if there is a way, please do share it with me.
EDIT: I'm aware that there might be similar functions already built-in to MATLAB, I'm just looking to increase my knowledge and skill in MATLAB-coding.
I don't think you can check if a function treats an input as a filehandle. I agree on the try/catch approach:
function foo(input_func, path)
% for testing
if nargin==0
input_func = #(s) fprintf('Filename: %s\n', s.name);
path = pwd;
end
% check function handle
assert(isa(input_func, 'function_handle'), 'input_func is not a valid function handle!')
% get folder contents
listing = dir(path);
for i_item = 1:length(listing)
item = listing(i_item);
if ~item.isdir
try
input_func(item)
catch E
warning('Function threw error for %s', item.name)
end
end
end
If you try replacing the 'fprintf' with eg. sin(), you should get a bunch of warnings and no nasty crashes.
Something you might want to look into is try/catch:
http://www.mathworks.com/help/matlab/ref/try.html
This way you could try evaluating your function with your file(s), and if it doesn't like it, catch should capture the errors and perhaps execute a corresponding error message

MatLab operator overloading [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do properties work in Object Oriented MATLAB?
I have been using MatLab for quite some time but started using OOP just recently.
I have a class that is a simple linked list (it can be anything really). A few methods are declared in the class. Is it possible for the methods to modify the instance from which those are called?
instance.plotData() cannot modify any properties of the instance .
I have to return the instance for the function to actually have some effect on the instance itself:
instance = instance.plotData();
This seems really cumbersome. Is there a better way of achieving the task?
Addition:
classdef handleTest < handle
properties
number
end
methods
function addNode(this)
a = length(this);
this(a+1) = handleTest;
end
end
end
If i call:
x = handleTest
x.addNode()
then x has still only one node.
A possible solution is to derive from the handle class, i.e. use something like
classdef YourClass < handle
function plotData(obj)
... modify the obj here ...
end
end
However, this also has implications, if you copy the instance, i.e. if you do an
a = YourClass(...);
b = a;
then b is an alias for a and whenever you change a, you also modify b and vice
versa (meaning the data is only stored once in the background).
There is the Matlab documentation for handle classes and the difference to value classes.

Is there a function head in mathematica that can be used to define an input type?

I am defining a function that takes as input a function and I want to specify it in the input type i.e. Operat[_?FunctionQ]:=...
But there is no functionQ as of yet in mathematica. How do I get aroud this except not specifying any type at all.
Any ideas?
Oh!
This: Test if an expression is a Function?
may be the answer i am looking for. I am reading further
Is the solution proposed there robust?, i.e.:
FunctionQ[_Function | _InterpolatingFunction | _CompiledFunction] = True;
FunctionQ[f_Symbol] := Or[
DownValues[f] =!= {},
MemberQ[ Attributes[f], NumericFunction ]]
FunctionQ[_] = False;
The exhibited definition has great utility. The question is: what exactly constitutes a function in Mathematica? Pure functions and the like are easily to classify as functions, but what about definitions that involve pattern-matching? Consider:
h[g[x_]] ^:= x + 1
Is h to be considered a function? If so, it will be hard to identify as it will entail examining the up-values of every symbol in the system to make that determination. Is g a function? It has an up-value, but g[x] is an inert expression.
What about head composition:
f[x_][y_][z_] := x + y + z
Is f a function? How about f[1] or f[1][2]?
And then there are the various capabilities like JLink and NETLink:
Needs["JLink`"]
obj = JavaNew["java.util.Date"]
obj#toString[]
Is obj#toString a function?
I hate to bring up these problems without offering solutions -- but I want to emphasize that the question as to what constitutes a function in the Mathematica context is a tricky one. It is tricky from both the theoretical and practical standpoints.
I think that the answer to whether the exhibited function test is complete really depends upon the types of expressions that you will be feeding it in your specific application.

Get the list of functions loaded in R's global environment [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there a way to get a vector with the name of all functions that one could use in R?
Hi
I would like to get from R the list of functions loaded in the environment.
I know ls() that gives the list of objects loaded. But some objects are not functions.
I would like to clean my env from the functions but not from the other objects (matrices, array etc) that contain some of my result that dont want to lose.
Any idea?
See ?lsf.str
X <- lsf.str()
as.vector(X) # just for printing purposes, you can use the vector in rm()
rm(list=X)
ok, I have a proposal
rm(list=ls()[sapply(ls(), function(obj) "function"==class(eval(parse(text = obj)))[1])])
I am sure there is something more elegant.