Handler to fundamental type variable - matlab

Is it possible in MATLAB to have a reference to a fundamental type without wrapping it in a class?
Example:
A = 5;
RefToA = GetRef(A);
RedToA.Value = 10;
A
This should prints 10 not 5.
Are there something like GetRef and .Value?

Related

Do properties in F# classes double memory used in private fields?

F# classes have the nice property that arguments automatically become immutable private fields. If I want to make one such field available externally I can create a property, like I in the code below:
type MyClass (i: int list) =
member this.I with get() = i
member this.foo x = i.Head + x
let mc = MyClass [0..10]
mc.foo 10 // 10
mc.I // [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
Does I in the code above double the amount of memory used for i or is it just a function that returns the value of i?
(Of course this is only relevant if the argument uses a lot of memory, which is not the case in the example above)
No: i gets stored as a private field inside of MyClass; MyClass.I is a property whose get function returns the value of said field.
list<'T> is a reference type, so persisting it inside of the class is effectively a shallow copy and will not duplicate the data inside of the list.

codegen error: The left-hand side has been constrained to be non-complex, but the right-hand side is complex

I am new to matlab and am trying to compile legacy matlab code into C. I come across the following error when doing so:
??? The left-hand side has been constrained to be non-complex, but the
right-hand side is complex. To correct this problem, make the
right-hand side real using the function REAL, or change the initial
assignment to the left-hand side variable to be a complex value using
the COMPLEX function.
The code that it complains on is in the comments of the code below:
function [z_out,ovf_flag,ovf_cnt] = fxpt_sgn_saturate(z_in,Nb_out)
Nb_out=(Nb_out<=0)+(Nb_out>0)*Nb_out;
max_val = 2^(Nb_out-1)-1;
min_val = -2^(Nb_out-1);
ovf_cnt = 0;
tmp_ind = find(real(z_in) > max_val);
z_in(tmp_ind) = max_val+1j*imag(z_in(tmp_ind)); // ERROR OCCURS HERE
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(real(z_in) < min_val);
z_in(tmp_ind) = min_val+1j*imag(z_in(tmp_ind));
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(imag(z_in) > max_val);
z_in(tmp_ind) = real(z_in(tmp_ind))+1j*max_val;
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(imag(z_in) < min_val);
z_in(tmp_ind) = real(z_in(tmp_ind))+1j*min_val;
ovf_cnt = ovf_cnt + numel(tmp_ind);
z_out = z_in;
ovf_flag = ~(ovf_cnt==0);
return
I don't particularly understand the code well. Any ideas how to fix this issue?
Thanks
When generating the code, you can use the -args flag to specify the size, class, and complexity of your input arguments. You can explicitly cast z_in as a complex number to ensure that the code generation succeeds.
codegen fxpt_sgn_saturate -args {complex(z_in), double(Nb_out)}
Alternately, if you're calling this function from within many other functions and are only calling codegen on the top-level function, then you'll want to explicitly cast the input as a complex datatype within your code prior to calling the function so that codegen can appropriately determine the complexity of the input.
function a(thing)
fxpt_sgn_saturate(complex(thing), 10);
end

How to make a Matlab structure constant once it is already created?

Suppose I have a function defined in foo.m. This function can take a parameter thing of type struct. Once foo makes changes to thing, I want to "lock" thing so that it can no longer be changed. I essentially want to make it constant. I want to do this to ensure it isn't modified further down the line. How do I do this in Matlab?
You should
define the variable in the function to be persistent
lock your function in the memory using mlock.
mlock locks the currently running function in memory so that subsequent clear functions do not remove it. Locking a function in memory also prevents any persistent variables defined in the file from getting reinitialized.
Solution 1: Good if you don't know what form your struct will have in advance
You could 'capture' that variable with an anonymous function handle and only refer to your structure with that from now on. An anonymous function handle captures the state of the workspace at the time it is created. You will be able to access its elements as if it were the original struct, but if you try to assign to it, you'll generate an error.
E.g.
>> S_.a = 1;
>> S_.b = 2;
>> S = #() S_;
>> S_.a = 3;
>> S_
S_ =
scalar structure containing the fields:
a = 3
b = 2
>> S()
ans =
scalar structure containing the fields:
a = 1
b = 2
It's almost identical in syntax, except for the annoyance that you'll have to call it with ().
I've used it on the terminal here, but obviously it can easily also be used in the context of a function.
Small caveat; if you redefine and overwrite the anonymous function, obviously, this backfires, since it will inherit whatever new workspace it had access to at the time of the redefinition.
Solution 2: Good if you know your struct's form in advance:
Assume you know in advance that your struct will only contain fields a and b. Create a class with the same properties restricting 'SetAccess', e.g.
classdef ConstStruct
properties (GetAccess = 'public', SetAccess = 'private')
a
b
end
methods
%constructor
function obj = ConstStruct(S)
obj.a = S.a;
obj.b = S.b;
end
end
end
Then in your main code:
>> MyStruct = struct('a',1,'b',2)
MyStruct =
a: 1
b: 2
>> MyStruct = ConstStruct(MyStruct)
MyStruct =
ConstStruct with properties:
a: 1
b: 2
>> MyStruct.a
ans =
1
>> MyStruct.a = 2
You cannot set the read-only property 'a' of 'ConstStruct'.

1-line try/catch equivalent in MATLAB

I have a situation in MATLAB where I want to try to assign a struct field into a new variable, like this:
swimming = fish.carp;
BUT the field carp may or may not be defined. Is there a way to specify a default value in case carp is not a valid field? For example, in Perl I would write
my $swimming = $fish{carp} or my $swimming = 0;
where 0 is the default value and or specifies the action to be performed if the assignment fails. Seems like something similar should exist in MATLAB, but I can't seem to find any documentation of it. For the sake of code readability I'd rather not use an if statement or a try/catch block, if I can help it.
You can make your own function to handle this and keep the code rather clear. Something like:
swimming = get_struct(fish, 'carp', 0);
with
function v = get_struct(s, f, d)
if isfield(s, f)
v = s.(f); % Struct value
else
v = d; % Default value
end
Best,
From what I know, you can't do it in one line in MATLAB. MATLAB logical constructs require explicit if/else statements and can't do it in one line... like in Perl or Python.
What you can do is check to see if the fish structure contains the carp field. If it isn't, then you can set the default value to be 0.
Use isfield to help you do that. Therefore:
if isfield(fish, 'carp')
swimming = fish.carp;
else
swimming = 0;
end
Also, as what Ratbert said, you can put it into one line with commas... but again, you still need that if/else construct:
if isfield(fish,'carp'), swimming = fish.carp; else, swimming = 0;
Another possible workaround is to declare a custom function yourself that takes in a structure and a field, and allow it to return the value at the field, or 0.
function [out] = get_field(S, field)
if isfield(S, field)
out = S.(field);
else
out = 0;
end
Then, you can do this:
swimming = get_field(fish, 'carp');
swimming will either by 0, or fish.carp. This way, it doesn't sacrifice code readability, but you'll need to create a custom function to do what you want.
If you don't like to define a custom function in a separate function file - which is certainly a good option - you can define two anonymous functions at the beginning of your script instead.
helper = {#(s,f) 0, #(s,f) s.(f)}
getfieldOrDefault = #(s,f) helper{ isfield(s,f) + 1 }(s,f)
With the definition
fish.carp = 42
and the function calls
a = getfieldOrDefault(fish,'carp')
b = getfieldOrDefault(fish,'codfish')
you get for the first one
a = 42
and the previous defined default value for the second case
b = 0

loop starting from given index

Considering the following javascript, what's the best way to write this loop in coffee script, given the initial index is greater than 0:
function mixin(target, source, methods) {
for (var i = 2, l = arguments.length; i < l; i++){
var method = arguments[i];
target[method] = source[method].bind(source)
}
}
Automatic code converters suggest use a while loop like this:
mixin = (target, source, methods) ->
i = 2
l = arguments.length
while i < l
method = arguments[i]
target[method] = source[method].bind(source)
i++
Is there a cleaner way to do this?
You'd usually use a splat in CoffeeScript when defining your mixing function:
The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ..., both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.
So you'd say:
mixin = (target, source, methods...) ->
# splat ----------------------^^^
for method in methods
target[method] = source[method].bind(source)
and your problem goes away. The splat in the argument list will collect all the arguments after source into a methods array for you so you won't have to worry about arguments at all; the splat also makes the function's signature nice and obvious.
Use an exclusive range (triple dot, excludes the number at the highest.
for i in [2...arguments.length]
method = arguments[i]
target[method] = source[method].bind(source)
If you have 5 things in your args, this will hit indexes 2, 3 and 4.