automatically assign class type in matlab - class

I'd like to obtain a class type of a variable and use it as a function in Matlab.
For example, say x is of class uint8. I can obtain this info by classtype=class(x).
What I'd like is to use it on a different variable automatically, such as:
y=classstype(y)
where y is of type logical for example.
How can I accomplish that?

It sounds like you're trying to cast the value of y to a different class. To this end, you could try using Matlab's cast() function.
In your specific instance, you could try:
y = cast(y, class(x))
This should get the class of variable x and cast variable y to that class.

The function class() returns the string with a class name. You can use it further using the function eval() which deals with strings as an input.

Related

Define Multiple Enums in a Single File in Matlab

Is it possible to define multiple enumerations in a single Matlab file? Or is it possible to have "local" enums in the same way we can define local funtions at the end of a file?
I am working on a project where it would be handy to have multiple enumeration classes, but it is annoying to use a classdef every time because it requires a separate file, and this means that there are lots of short files whose sole purpose it is to define enumerations. At the moment, each enumeration looks like this:
classdef exampleEnumType < uint32
enumeration
zero(0),
one(1),
two(2),
end
end
Is there a way to compactly define enumerations in Matlab so that I do not need a separate file for each (using Matlab 2021a)?
First of all, having lots of short files is the normal situation in MATLAB. Working around that is possible but oftentimes futile.
Traditionally in MATLAB, constant values are defined as a function. For example, pi is a function. It looks something like this:
function v = pi
v = 3.14159
By making the constant into a function, it is available from everywhere without first running code to define those constants.
An enumeration is nothing more than a series of constants. The same can be accomplished with a struct:
exampleEnumType = struct('zero',0, 'one',1, 'two',2);
Since fairly recently (R2019b), MATLAB allows dot indexing into the output of a function call, but you do need to use empty parenthesis in the function call. Thus, we can declare the above struct the same way we did with constants:
function v = exampleEnumType
v = struct('zero',0, 'one',1, 'two',2);
This allows to do exampleEnumType().zero (almost) like with the enum or with a struct variable.
So how do we extend this to defining multiple of these in a single file? If a common prefix is no problem, we can define a class with static member functions, each one declaring a constant:
classdef constants
methods(Static)
function v = pi
v = 3.14159
end
function v = exampleEnumType
v = struct('zero',0, 'one',1, 'two',2);
end
end
end
We now have constants.pi and constants.exampleEnumType().zero.
Alternatively, create a single function that returns a more complex struct as follows:
function v = constants
v.pi = 3.14159;
v.exampleEnumType = struct('zero',0, 'one',1, 'two',2);
This allows us to do constants().exampleEnumType.zero.
Note that the above will not work in the same way for MATLAB releases prior to R2019b. For older versions of MATLAB, the last method (a function constants) would be the best approach. The user would just need to do constants = constants; at the top of any function needing to use the constants. This shadows the function with a variable of the same name, so that constants.exampleEnumType.zero works as expected.
You can use a map...
exampleEnum = containers.Map( {'zero','one','two'}, {0,1,2} );
usage looks like
exampleEnum('zero') % = 0
I'm thinking you might want to use categorical arrays here, and stick "enumerations" of their valid values as constants in a common class.
classdef Constants
properties (Constant)
Foods = categorical(["apple", "banana", "pear"])
SupportedProtocols = categorical("http", "https", "ftp")
SpeedOfGravityMps = 9.86
end
end
If you want them to be true Matlab enumerations, then yeah, you're stuck with a separate file for each.

MATLAB - automatically apply obj references in function

when working with objects in Matlab I constantly have to type
"obj.x, obj.y"
Is there a way to automatically set my matlab functions to apply the obj. reference, so I can just type x and y.
currently i must type as follows:
z = function(obj)
z=obj.x+obj.y
i would like to type
z = function(obj)
z=x+y
No. Sorry; this is just how Matlab works; object references are always explicit.

Can MATLAB Coder generate a function that takes a pointer as input?

I would like to use MATLAB Coder to generate an executable (or a function in an object file) that accepts a pointer to an array as an input.
I used libpointer to create a pointer object and then tried to compile with the following codegen command:
codegen -config:lib foo -args {coder.typeof(pointer_object_name)}
The resulting error message reported that coder.typeof does not support the lipointer type.
My ultimate goal is to create something that can be called from another C function, with no MATLAB in sight, and receive a pointer to an array as an input. Can MATLAB Coder generate something like that?
#ryan-livingston asked for the signature of the function I would like MATLAB Coder to generate.
Suppose that samples is a pointer to an array of floats. I think I want MATLAB Coder to create a void foo(float *samples) that performs various computations on those floats and perhaps writes results to a file or socket.
Now that I have the attention of #ryan-livingston, I suppose I should ask the following.
Can Coder make functions such as resample work with pointers?
Are pointers already being used under the hood, making my concern unnecessary?
If you just generate code with a fixed-size array input, the generated code will be able to accept a pointer. For example:
function x = foo(x)
x = 2*x;
% You can use MATLAB fopen, fprintf, fwrite here to write x to a file
>> codegen foo -args zeros(10,20) -config:lib -report
produces the interface:
void foo(double x[200]);
which is the same as:
void foo(double *x);
because of array to pointer decay on calls in C.
Note that I've used the x = foo(x) syntax to have Coder pass x by reference to foo. Functions declared with the same variable as both input and output generally produce pass by reference when also called with the same variable as input and output at the callsite.

Array as a function parameter instead separate variables in Matlab

I need pass to a function (jacobian() in my case) a symbolic variable array is being creating dynamically. Say,
jacobian(handles{2}(t,y,paramlist),y)
where paramlist=[var1, var2, var3, ..., varN] has an arbitry size. All variables here are symbolic and have various names. MATLAB throw an error:
Not enough input arguments.
Knowing number of parameters in the function definition one can pass all parameters separately. Say, for n=3:
jacobian(handles{2}(t,y,paramlist(1),paramlist(2),paramlist(3)),y)
But what about the common case? It's a bad style of programming to write the function call for each fixed number of parameters. Is there a way to pass an array so as it would be treated as distinct variables?
You can convert paramlist to a cell array (using num2cell) and then use {:} indexing to create a comma separated list which you can then use this for indexing into handles{2}. This will make it such that each value of paramlist is passed as a separate subscript.
plistcell = num2cell(paramlist);
jacobian(handles{2}(t, y, plistcell{:}), y)

What does this matlab statement do

I have a statement in my MATLAB program:
f = #(A)DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus);
I understood that f is defined as the function handle to the function distancegauss which contains the parameters/arg list present inside the parentheses.
What does the variable A in #(A) do? Does it have any importance? While browsing I found that the variables within parentheses after # would be the input arguments for an anonymous function..
Can anyone explain what does that A do? Will this handle work even without that A after the # symbol ? Because it is already present as an argument to be passed after the function name.
Your code will create an anonymous function f which accepts one input A. In particular f will call the function DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus); where the value of A is whatever you input with f(A) and the other inputs must already exist in your workspace and will be passed to the function. Note: if the other variables don't exist you should get an error when calling f.
Now a reasonable question is why would you want to do this you could just call DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus); directly with whatever values you want, without having to worry about whether some of them exist.
There are two main reasons I can think of why you would do this (I'm sure there are others). Firstly for simplicity where your other inputs don't change and you don't want to have to keep retyping them or have users accidentally change them.
The other reason where you would want this is when optimizing/minimizing a function, for example with fminsearch. The matlab optimization functions will vary all inputs. If you want only vary some of them you can use this sort of syntax to reduce the number of input variables.
As to what A actually is in your case this will depend on what it does in DistanceGauss, which is not a standard MATLAB function so I suggest you look at the code for that.
"f(A)" or "f of A" or "The function of A" here has the handle "f"
DistanceGauss() here is another function that was defined elsewhere in your code.
You would set x_axis, Y_target, Y_initial, numOf, & modus before creating the function f. These arguments would stay the same for Function f, even if you try and set them again later.
'A' though, is different. You don't set it before you make the function. You can later operate on all values of A, such as if you plot the function or get the integral of the function. In that case, it would be performing the DistanceGauss function on every value of 'A', (though we can't see here what DistanceGauss function does. )
Anonymous function should be defined such as:
sqr = #(x) x.^2;
in which x shows the variable of the the function and there is no name for it (it is called anonymous!).
Although you can do something like this:
c = 10;
mygrid = #(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);
in which you are modifying an existing function ndgrid to make a new anonymous function.
In your case also:
f = #(A)DistanceGauss(A,x_axis,Y_target,Y_initial,numOf,modus);
This is a new anonymous function by modifying the function DistanceGauss that you may want to have a single variable A.
If you remove (A) from the code, then f would be a handle to the existing function DistanceGauss:
f = #DistanceGauss;
Now you can evaluate the function simply by using the handle:
f(A,x_axis,...)