Encounter with a strange Mask initialization Command - matlab

So in one of the mask in the model i came across an initialization command that i don't understand.
The logic is for an SR Flip Flop. That latches the output.
It has 1 parameter that takes in the initial state for output 1(Output is o and o(bar)).
Which has the following properties:
Name: MaskParam1
Value: 0
Type: Edit
Evaluate: True
Tunable: True
The command is written in the Initialization tab of the Mask Editor.
ini = (#1~=0);
The first thing that came to my mind was anonymous function handle, that returns value of the parameter. In this case would be 0.
So as (0 ~=0) = 0hence the initial output of SR will be 0.
When i type the following in matlab:
ini = (#1~=0);
I get an error of unexpected matlab expression.
So I tried another thing. Considering as the Parameter is refering to the masked parameter so if we take a variable:
x = 0;
% The default value for the mask parameter
ini = (#x~=0);
This will give an error that
Error: "x" was previously used as a variable, conflicting with its use here as the name of a function or command.
So my question is ini
ini = (#1~=0)
a function or a variable??enter code here

Related

getting the value from a checkbox in Matlab 2018

I am upgrading my Matlab from 2013b to 2018b and have found out that MathWorks have made quite a few changes to the GUI's.
One problem I am having is getting the value of checkbox. The line below is the code I used to use but now it doesn't work.
if get(handles.check_perf_attr,'Value') == 1
The error message is,
Undefined operator '==' for input arguments of type 'cell'.
So I tried the line below to just get the value that is being returned and then apply some logic.
tValue = get(handles.check_perf_attr,'Value');
However tValue is 2 x 1 cell which in (1, 1) = 0 & (2, 1) = 1. I don't really understand this as surely a checkbox can only be one value true (1) or false (0)?
get returns a cell array with values when applied to an array of handles.
Thus, I think your problem is that handles.check_perf_attr contains two handles, not one.
"Dot notation is a new syntax to access object properties starting in R2014b."
so try
if handles.check_perf_attr.Value == 1
or
tValue = handles.check_perf_attr.Value;

Matlab class set method call unexpectedly

Matlab specifies When [a] Set Method is Called
I ran into odd results, so I conducted a series of tests on the following class:
% #cScenInsts/cScenInsts.m
%-------------------------
classdef cScenInsts < matlab.mixin.Copyable
properties
TwinYrs = 5 % Default value
end % properties
methods
function o = cScenInsts( TwinYrs_in ) % Constructor
if exist('TwinYrs_in') && ~isempty( TwinYrs_in )
o.TwinYrs = TwinYrs_in ;
else
o.TwinYrs = o.TwinYrs ;
end % if
end % function cScenInsts()
function o = set.TwinYrs(o,TwinYrs_in)
o.TwinYrs = TwinYrs_in;
fprintf( '%s: Property TwinYrs = %g\n', mfilename, o.TwinYrs );
end % function set.TwinYrs
end % methods
end % classdef
The else block is superfluous in this minimum working example, but in real life, I want it to invoke the set method, which sets the values of other dependent parameters.
Using the class definition above, I ran into mixed results in terms of whether they seemed to follow the rules for when a set method is called.
UNEXPECTED behaviour in the following command: "Assigning a property to its default value that is specified in the class definition" shouldn't trigger set method, but it does.
>> o = cScenInsts;
cScenInsts: Property TwinYrs = 5
As well, "As an optimization, if MATLAB determines that a property value does not change as a result of an assignment referencing the property, MATLAB does not call the property set method". It seems that if the property is on the LHS and RHS of the assignment and the value doesn't change, the set method isn't called. This should apply above, as it is the else block that executes. The above result shows that it doesn't apply, which is the effect I seek. My anxt is that I don't know how much confidence I can have in the reliability of this behaviour in all circumstances when it seems to contradict the optimization provision.
EXPECTED behaviour in the following command:
>> o = cScenInsts(3);
cScenInsts: Property TwinYrs = 3
UNEXPECTED behaviour in the following command: "Assigning a property to its default value that is specified in the class definition" shouldn't trigger set method, but it does.
>> o = cScenInsts(5);
cScenInsts: Property TwinYrs = 5
EXPECTED behaviour in the following command:
>> o.TwinYrs = 3;
cScenInsts: Property TwinYrs = 3
EXPECTED behaviour in the following command, since the property's AbortSet attribute not set to true
>> o.TwinYrs = 3;
cScenInsts: Property TwinYrs = 3
UNEXPECTED behaviour in the following command: "Assigning a property to its default value that is specified in the class definition" shouldn't trigger set method, but it does.
>> o.TwinYrs = 5;
cScenInsts: Property TwinYrs = 5
AMBIGUOUS behaviour in the following command: On one hand, "[a]ssigning a property to its default value that is specified in the class definition" shouldn't trigger set method, but it does. On the other hand, it can also be considered expected behaviour, since the property's AbortSet attribute not set to true
>> o.TwinYrs = 5;
cScenInsts: Property TwinYrs = 5
Can anyone please explain the unexpected and/or ambiguous results?
I'll address each of the confusing bullet points you mention from this list of cases when the property set method IS NOT called:
Initializing default values in class definitions when loading the class
I believe this is specifically referring to creating a class object by loading it from a MAT-file (i.e. using the loadobj method). When loading the property values, they are simply copied without passing them to the set method.
Assigning a property to its default value that is specified in the class definition
I believe this is specifically referring to when MATLAB initially creates the object and sets its default values. It does this without passing the values to any set methods first. To see this, you can add this line to the very beginning of your class constructor:
disp(o);
When you run your code, you'll see that a default object with the default property values is already created for you upon entering the constructor, before you've even done anything with the input arguments. These properties are set without invoking any set methods (as the bullet point states). Any subsequent changes to the property, like when you set them in your if-else statement, DOES still invoke the set method, as expected.
You may notice then that your else statement is actually unnecessary in this case, since the defaults are already set. Removing the else statement will give you your expected behavior for:
o = cScenInsts;
As an additional aside, since you are subclassing the matlab.mixin.Copyable class (which has handle class behavior), you don't need to return an object from your set methods:
function set.TwinYrs(o, TwinYrs_in)
...
As an optimization, if MATLAB determines that a property value does not change as a result of an assignment referencing the property, MATLAB does not call the property set method.
This statement is a little unclear. As you already noted, leaving the AbortSet attribute unset (i.e. it is set to false by default) means that the set method will still be called even when setting a property to the same value. The statement above seems to suggest that under some circumstances, even when the AbortSet attribute is false, MATLAB may still decide to forego calling the set method. If so, it's not clear what those conditions are under which that optimization is used.
Removing the else statement as I suggest above, here are the expected results for some of your examples above:
>> o = cScenInsts; % Set method not invoked, default value used
>> o = cScenInsts(3);
cScenInsts: Property TwinYrs = 3 % Set method invoked, overriding default value
>> o = cScenInsts(5);
cScenInsts: Property TwinYrs = 5 % Set method invoked, even though same as default value
% (since AbortSet is false)
>> o.TwinYrs = 5;
cScenInsts: Property TwinYrs = 5 % Set method invoked, even though same as current value
% (since AbortSet is false)
This is the answer from TMW:
...the statement:
"As an optimization, if MATLAB determines that a property value
does not change as a result of an assignment referencing the
property, MATLAB does not call the property set method."
...is plainly incorrect. This optimization does not exist -- the
only time MATLAB forgoes calling the setter due to an assignment not
changing the value is when "AbortSet" is set to true.<...snip...>
As for the other unclear bullet points:
"Initializing default values in class definitions when loading the
class"
This refers to loading the class definition which happens when doing
“?” or when first constructing the class. This is the
step that parses and compiles the class definition and sets the
DefaultValue property of the meta.property object accessible from
the meta.class object returned from ?. This has nothing
to do with loading instances of a class from a MAT-File or loadobj.
"Assigning a property to its default value that is specified in
the class definition"
This bullet means that the set-function is not called when MATLAB
assigns a default value to a property when making a new instance of
a class. This refers to the assignment of the default value during
property initialization. As we suspected, it does not refer to any
other assignment to a value that happens to be equal to the default
value.
I will go ahead and submit the documentation update request...
Thank you all for having chimed in.

Call a script with definitions in a function

We have a script that defines values to names similar to #define in c. For example:
script.m:
ERR_NOERROR = 0;
ERR_FATAL = 1;
This script already exists and is used for value replacement when reading data from files.
Now we have a function (or more) that does some analysis and we would like to use the same definition in this function to avoid magic numbers. But when the script is called from the function we get an error.
Attempt to add "ERR_NOERROR" to a static workspace.
See MATLAB Programming, Restrictions on Assigning to Variables for details.
And this does not help much in the understanding of the problem.
The question is how can we make these definitions visible/usable in the functions with having to copying it every time.
Example:
function foo = bar(a)
run(script.m) %also tried running it without the run command
if a == ERR_NOERROR
foo = 5;
else
foo = 6;
end
end
edit:
There was a nested function,below in the function which I was not aware of. This explains the problem.
This kind of scoping error happens when you use nested or anonymous function within a function. The solution is well documented.
To your case, you can avoid nested function, or "Convert the script to a function and pass the variable using arguments", as the documentation suggests.
EDIT: I should have made it clear that the error occurs even if the script is not called within the nested function. Similar scenario is that, in debug mode (by setting up a break point), it will be an error if one tries to create a temporal variable to test something.
This is not a direct answer, rather a recommendation to switch to another method, which will not be mixing scope and workspace.
Instead of defining your constant in a script, you could make a class containing only constant properties. ex: code for error_codes.m:
classdef error_codes
% ---------------------------------------------------------------------
% Constant error code definition
% ---------------------------------------------------------------------
properties (Constant = true)
noerror = 0 ;
fatal = 1 ;
errorlvl2 = 2 ;
errorlvl3 = 3 ;
warning = -1 ;
% etc ...
end
end
I use this style for many different type of constants. For tidiness, I groups them all in a Matlab package directory (The directories which starts with a + character.
The added benefit of using constant class properties is the safety that the values cannot be changed in the middle of the code (your variables defined in a script could easily be overwritten by a careless user).
So assuming my file error_codes.m is placed in a folder:
\...somepath...\+Constants\error_codes.m
and of course the folder +Constants is on the MATLAB path, then to use it as in your example, instead of calling the script, just initialise an instance of the class, then use the constant values when you need them:
function foo = bar(a)
ERR = Constants.error_codes ;
if a == ERR.noerror
foo = 5;
else
foo = 6;
end
or it can works in switch statement too:
switch a
case ERR.noerror
foo = 5 ;
case ERR.warning
foo = 42 ;
case ERR.fatal
foo = [] ;
end

OMShell returns String but doesn't recognize it

For one of my models, it is required to read the final value of all variables and set them as initial value for the next simulation. My real problem is due to types defined in OMShell. As can be seen in the scripting commands of OpenModelica, there are String type and "VariableName", "TypeName" types. To elaborate the difference:
// The following loads the Standard Modelica Library
>> loadModel(Modelica)
true
// The following throws an error
>> loadModel("Modelica")
The reason is that the loadModel function doesn't expect a string variable. It expects the name of the model. Returning my problem, I tried to use val function as in the following, so that I can give the value as the initial value of the next simulation.
>> final_time := 200;
>> myVarValue := val(myVar, final_time);
This can be done for each variable by using a for-loop, I thought as I have several variables and I realized the problem at this point.
// Get the list of all variables
>> myVarList := readSimulationResultVars(currentSimulationResult);
>> size(myVarList)
{724}
// The problem is that this list contains strings
>> myVarList[1]
"mySubSystem.myComponent.myPin.v"
// Following throws an error as it doesn't expect a string
>> val(myVarList[1], final_time)
How can I remove "" from the string that OMShell returns to me? I need to convert "myVar" to myVar so that I can use it as an input for the functions of OMShell.
You can use the stringVariableName function.
>>> vars:=OpenModelica.Scripting.readSimulationResultVars(currentSimulationResult)
{"r","time"}
>>> val(stringVariableName(vars[1]), 0.0)
1.0

Passing a variable out of local functions

I'm having some trouble with local functions within my code so I've pasted a simple example below:
function [avg,testvar] = test(x) %Warning
n = length(x);
avg = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
One can probably see what I'm attempting; to pass testvar out of the local functions. However Matlab returns the warning:
"The function return value 'testvar' might be unset"
with respect to the line I've commented "%Warning".
What's the best way of getting around this?
You need to specify the value of the second output of test(). Otherwise how can MATLAB know what its value is supposed to be? It doesn't know the second output of mymean() should be routed to the second output of test(). Perhaps this will solve your problem.
function [avg,testvar] = test(x) %Warning
n = length(x);
[avg, testvar] = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
The variables between brackets after function are the output variables.
In your first function, you did not assign any value to testvar hence the warning. If you add testvar = 123; in the first function, the warning goes away. Or you can remove testvar from the output variables, leaving:
function avg = test(x)