MatLab operator overloading [duplicate] - function

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.

Related

Indexing the name of a function in a for loop in Julia

I'm trying to write a for loop to generate multiple functions. I would like to iterate on the name of the functions as well but I can't seem to make it work. Here's what I want to do:
for i = 1:n
h_[i](x) = i*x
end
I know this doesn't work but I would like something like that.
Thanks!
As #laborg mentioned, quite often you don't need/want to use metaprogramming. Since you already try to use array indexing syntax (h_[i]) perhaps you should simply create a vector of functions, for example like so:
h_ = [x->i*x for i in 1:n]
Here, x->i*x is an anonymous function - a function that we don't care to give a name. Afterwards you can use actual array indexing to access these different functions and call them.
Demo:
julia> n = 3;
julia> h_ = [x->i*x for i in 1:n];
julia> h_[1](3)
3
julia> h_[2](3)
6
julia> h_[3](3)
9
No metaprogramming involved.
(On a side note, in this particular example a single function h(x;i) = i*x with a keyword argument i would probably the best choice. But I assume this is a simplified example.)
You have to evaluate the name of your function:
for i = 1:n
f = Symbol(:h_,i)
#eval $f(x) = $i*x
end
More on this:
https://docs.julialang.org/en/v1/manual/metaprogramming/
As a general note on meta programming in Julia: It really helps to think twice if meta programming is the best solution, especially as Julia offers a lot of other cool features, e.g. multiple dispatch.

Lua - Should I use ":" when defining functions in tables if not using the "self" keyword?

This is more of a design philosophy question as I already know you shouldn't call a function with : (object-oriented syntactic sugar) if the function has been defined without the self keyword by using .. But the problem is that programmers using a library I have created tend to not read the documentation and run into the question of "how should I call your function?", so I end up always defining functions using the method below:
local tbl = {};
function tbl:Add(a, b)
return a + b;
end
I have installed Luacheck (in VS Code) and it often complains when I use this syntax and not use the self referential keyword. It says: [luacheck] unused argument "self". Is there any problem with this in terms of performance (or is there a way of disabling Luacheck in VS Code)?
I prefer writing functions in this style as opposed to the style below:
function tbl.Add(_, a, b)
return a + b;
end
It seems a pain to have to add a dummy variable at the start of the parameter list.
EDIT: Another problem is what if you had many tables that implement a function with the same name and want to iterate over them but some implementations do not use the self argument and others do? It would be very tedious and bad design to check what type of table it is to call the function correctly.
What is the preferred style? A bit confused in general about this warning. What are your thoughts? Thanks.
if you're not using the self argument you can just do
function tbl.Add(a, b)
return a + b;
end
no need to use a dummy variable.
You just need to be sure then that you also call it with a . and not a :
so
local someValue = tbl.Add(1, 3)
for example and not
local someValue = tbl:Add(1, 3)

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

Ignoring an output from a Matlab function [duplicate]

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;

What is the difference between a property and an instance variable?

I think I've been using these terms interchangably / wrongly!
Iain, this is basically a terminology question and is, despite the "language-agnostic" tag associated with this question, very language/environment related.
For design discussions sake, property and instance variable can be used interchangeably, since the idea is that a property is a data item describing an object.
When talking about a specific language these two can be different. For example, in C# a property is actually a function that returns an object, while an instance variable is a non-static member variable of a class.
Hershi is right about this being language specific. But to add to the trail of language specific answers:
In python, an instance variable is an attribute of an instance, (generally) something that is referred to in the instance's dictionary. This is analogous to members or instance variables in Java, except everything is public.
Properties are shortcuts to getter/setter methods that look just like an instance variable. Thus, in the following class definition (modified from Guido's new style object manifesto):
class C(object):
def __init__(self):
self.y = 0
def getx(self):
if self.y < 0: return 0
else: return self.y
def setx(self, x):
self.y = x
x = property(getx, setx)
>>> z = C()
>>> z.x = -3
>>> print z.x
0
>>> print z.y
-3
>>> z.x = 5
>>> print z.x
5
>>> print z.y
5
y is an instance variable of z, x is a property. (In general, where a property is defined, there are some techniques used to obscure the associated instance variable so that other code doesn't directly access it.) The benefit of properties in python is that a designer doesn't have to go around pre-emptively encapsulating all instance variables, since future encapsulation by converting an instance variable to a property should not break any existing code (unless the code is taking advantage of loopholes your encapsulation is trying to fix, or relying on class inspection or some other meta-programming technique).
All this is a very long answer to say that at the design level, it's good to talk about properties. It is agnostic as to what type of encapsulation you may need to perform. I guess this principle isn't language agnostic, but does apply to languages beside python.
In objective c, a property is an instance variable which can take advantage of an overloaded dot operator to call its setter and getter. So my.food = "cheeseburger" is actually interpreted as [my setFood:"cheeseburger"]. This is another case where the definition is definitely not language agnostic because objective-c defines the #property keyword.
code example done in C#
public class ClassName
{
private string variable;
public string property
{
get{ return variable; }
set { variable = value; }
}
}
Maybe thats because you first came from C++ right?!
In my school days I had professors that said class properties or class atributes all the time. Since I moved to the Java C# world, I started hearing about members. Class members, instance members...
And then Properties apear! in Java and .NET. So I think its better for you to call it members. Wheather they are instance members (or as you called it instance variable) or class Members....
Cheers!
A property can, and I suppose mostly does, return an instance variable but it can do more. You could put logic in a property, aggregate values or update other instance variables etc. I think it is best to avoid doing so however. Logic should go into methods.
In Java we have something called JavaBeans Properties, but that is basically a instance variable that follows a certain naming pattern for its getter and setter.
At add to what has been said, in a langauge like C#, a property is essentially a get and set function. As a result, it can have custom logic that runs in addition to the getting/setting. An instance variable cannot do this.
A property is some sort of data associated with an object. For instance, a property of a circle is its diameter, and another is its area.
An instance variable is a piece of data that is stored within an object. It doesn't necessarily need to correspond directly with a property. For instance (heh), a circle may store its radius in an instance variable, and calculate its diameter and area based on that radius. All three are still properties, but only the radius is stored in an instance variable.
Some languages have the concept of "first class" properties. This means that to a client application, the property looks and is used like an instance variable. That is, instead of writing something like circle.getDiameter(), you would write circle.diameter, and instead of circle.setRadius(5), you would write circle.radius = 5.
In contrast to the other answers given, I do think that there is a useful distinction between member variables and properties that is language-agnostic.
The distinction is most apparent in component-oriented programming, which is useful anywhere, but easiest to understand in a graphical UI. In that context, I tend to think of the design-time configuration of a component as manipulating the "properties" of an object. For example, I choose the foreground and background colors, the border style, and font of a text input field by setting its properties. While these properties could be changed at runtime, they typically aren't. At runtime, a different set of variables, representing the content of the field, are much more likely to be read and written. I think of this information as the "state" of the component.
Why is this distinction useful? When creating an abstraction for wiring components together, usually only the "state" variables need to be exposed. Going back to the text field example, you might declare an interface that provides access to the current content. But the "properties" that control the look and feel of the component are only defined on a concrete implementation class.