S-function documentation that "S-function level-1 supports vector inputs and outputs. DOES NOT support multiple input and output ports" - matlab

I read in S-function documentation that "S-function level-1 supports vector inputs and outputs. DOES NOT support multiple input and output ports".
Does the second sentence mean the input and output dimension must be the same?
I have been using S-function level-1 to do the following:
[a1, b1] = choose_cells(c, d);
where a1 and b1 are outputs, c and d are inputs. All the variables are having a single value, except d is an array with 6 values.
Referring to the image attached, we all know that in S-function block, the input dimension must be SAME as output dimension, else we will get error, in this case, the input dimension is 7 while the output dimension is 2, so I have to include the "Terminator" blocks in the diagram for it to work perfectly, otherwise, I will get an error.
My problem is, when the system gets bigger, the array d could contain hundreds of variables, using this method, it means I would have to add hundreds of "Terminator" blocks in order to get this work, this definitely does not sound practical.
Could you please suggest me a wise way to implement this?
http://imgur.com/ib6BTTp
http://imageshack.us/content_round.php?page=done&id=4tHclZ2klaGtl66S36zY2KfO5co
Updated: actually I have been trying to convert my level-1 S-function to level-2 but I got stuck at calling another sub function at function Output(block) trying to look for other threads but to no avail, do you mind to provide related links?
My output depends on a lot processing with the inputs, this is the reason I need to call the sub-function in order to calculate and then return output values, all the examples that I can see are calculating their outputs directly in "function Output(block)", in my case I thought it is not possible.
I then tried to use Interpreted Matlab Function block but failed due to the output dimension is NOT the same as input dimension, also it does not support the return of more than ONE output................

Level-1 s-function supports single input and single output port. These ports must be vectors. But there is no restriction on the length. Input and output can have different lengths. You can use selector block to select only relevant data. You do not need to use Bus in the output.
There is also no restriction on calling other sub-functions from Output. If your sub-function is not in the same file it must be in the path or in the current directory.
If your MATLAB code is compatible with MATLAB Function block, I recommend using that block. It is simpler to setup and use.

Related

How can I optimize machine learning hyperparameters to be reused in multiple models?

I have a number of datasets, to each of which I want to fit a Gaussian process regression model. The default hyperparameters selected by fitrgp seem subjectively to produce less-than-ideal models. Enabling hyperparameter optimisation tends to result in a meaningful improvement but occasionally produces extreme overfitted values and is a computationally hungry process which prohibits an optimization for every model anyway.
Since fitrgp simply wraps bayesopt for its hyperparameter optimization, is it possible to call bayesopt directly to minimize some aggregate of the loss for multiple models (say, the mean) rather than the loss for one model at a time?
For example, if each dataset is contained in a cell array of tables tbls, I want to find a single value for sigma which can be imposed in calls to fitrgp for each table:
gprMdls = cellfun(#(tbl) {fitrgp(tbl,'ResponseVarName', 'Sigma',sigma)}, tbls);
Where numel(tbls) == 1 the process would be equivalent to:
gprMdl = fitrgp(tbls{1},'ResponseVarName', 'OptimizeHyperparameters','auto');
sigma = gprMdl.Sigma;
but this implementation doesn't naturally extend to a result where a single Sigma value is optimized for multiple models.
I managed this in the end by directly intervening in the built-in optimization routines.
By placing a breakpoint at the start of bayesopt (via edit bayesopt) and calling fitrgp with a single input dataset, I was able to determine from the Function Call Stack that the objective function used by bayesopt is constructed with a call to classreg.learning.paramoptim.createObjFcn. I also captured and stored the remaining input arguments to bayesopt to ensure my function call would be exactly analagous to one constructed by fitrgp.
Placing a breakpoint at the start of classreg.learning.paramoptim.createObjFcn and making a fresh call to fitrgp I was able to capture and store the input arguments to this function, so I could then create objective functions for different tables of predictors.
For my cell array of tables tbls, and all other variables kept as named in the captured createObjFcn scope:
objFcns = cell(size(tbls));
for ii = 1:numel(tbls)
objFcn{ii} = classreg.learning.paramoptim.createObjFcn( ...
BOInfo, FitFunctionArgs, tbls{ii}, Response, ...
ValidationMethod, ValidationVal, Repartition, Verbose);
end
An overall objective function can then be constructed by taking the mean of the objective functions for each dataset:
objFcn = #(varargin) mean(cellfun(#(f) f(varargin{:}),objFcns));
I was then able to call bayesopt with this objFcn along with the remaining arguments captured from the original call. This produced a set of hyperparameters as required and they seem to perform well for all datasets.

Simulink with if/else and different signal dimension

I need to implement a if/else in simulink to find out if a input is a scalar value or a matrix. Please see, the diagram below :
Given:
Block(1) - is a input that can be a scalar "1" or a matrix "[[0 15];[5 10]]"
Block(2) - must return the signal dimension of the input. Ex: 1 for scalar and >1 for a matrix
The requirements are:
Everything must work interpreted or compiled (Simulink coder)
The final output of blocks (4) and (5) are scalars
I have average understanding of CMexSFunctions. So if I need to implement one to solve the problem it is ok
So far, I have had the following problems:
I don't at all if what I am planning to do is feasible
I don't know how to implement Block(2) to work on compiled mode
Even though there is a if/else, simulink performs a pre-check before running to verify if all signal dimensions are ok. During this check, it gives a error saying ex: that Block(5) has a input of matrix
Any Clues?
Block(2) is the easiest part which can be implemented using the "Probe" block in Simulink library. Your Input at port 1 must be variable sized signal since you are expecting a scalar or matrix.
I assume you are feeding Input(1) to blocks 4 and 5. At model compile time Simulink does not know which one of these blocks are going to run based on the input size. So Simulink needs to assume both blocks may get scalar or matrix. You need to make blocks 4 and 5 not throw error for both scalar and matrix even though they will be used only for one type at run-time.
If you are not able to do this, for the scalar case a simple work around is to place a Selector before block 5 that selects the first sample always. This will let Simulink know that the input to block 5 is always a scalar.

Simulink signal from data generated by a fcn() block

In simulink I have a function block. Basically it contains
function y=fcn(u)
if u==1
a=[0,...,1];
b=[1,...,2];
end
y=[a',b'];
%y=struct('time',a,'value',b); %Second option
I want to use these arrays as a signal. As you see I have tried two options, making an output as an array and as a structure, non of them work for me.
In short, I'd like to be able to connect a scope to the output of the function and see the signal generated by (a,b). The reason I want to do it from a Simulink block is that I can just switch between many options of signals without having to build again the model. More over, I'd prefer that if the simulation time is bigger than whatever is specified in a then the signal keeps the last value of b.
p.s. I have tried this using a From Workspace block and it works fine.

using from workspace block in simulink

how to use the "from workspace block in simulink" ?
I have tried using the from workspace block by given 10*2 matrix as input. it is appending some extra data along the data I have given .
and I have such 3 such blocks and want to know how I merge them.
Read the documentation. Simulink is time-based so the data in your From Workspace block must be as a function of time. Does your 10 x 2 matrix represent a signal as a function of time? If so, it needs to be as follows:
A two-dimensional matrix:
The first element of each matrix row is a
time stamp.
The rest of each row is a scalar or vector of signal
values.
The leftmost element of each row is the time stamp of the
value(s) in the rest of the row.
10 values isn't very much, it's likely that Simulink will need additional data points at intermediate times, if you have the Interpolate Data check box ticked. If not, "the current output equals the output at the most recent time for which data exists".
I think you may have a misunderstanding of the variables intended to be read by the FromWorkspace block.
The block expects a time series defining the value at various points in the simulation.
The From Workspace block help should point you in the right direction on this. Mathworks Help Documentation
I believe that something like the following would work for you:
>> WorkspaceVar.time=0;
>> WorkspaceVar.signals.values=zeros(10,2)
>> WorkspaceVar.signals.dimensions = [10,2]

When using a multiple-output matlab function, do i need to callback all variables?

When using a multiple-output matlab function, do i need to callback all variables? or can I just take the first two variables? (if so..is it not recommended?)
lets say in function.m
[a, b, c] = function( )
in main.m
[var1, var2] = function;
When calling (almost) any function in matlab you can request fewer outputs than it specifies. So, yes the example you give should work perfectly fine.
There are some clever things you can do with this, such as using nargout within a function to see how many output arguments have been requested and only calculating the values that have been requested as an optimisation trick.
It depends on the definition of the function, and exactly which of the outputs you want to get.
Not all the function allow to do it, you can find all the options for each function in the beginning of the help documentation on the specific function.
If you want only the 2nd, or 3rd outputs, and you want also to save the computation-time of the results that does not interesting, you can use ~ option, like this (for versions 2009b and later):
[~, var1, var2]=function
Many functions allow for options to passed that change how the function behaves. I used/wrote various numerical solving functions a bit and one that nice amount of option, for instance is the LSMR function(s).
Otherwise, if you can manipulate the original either introduce an input(s) to do so before or at the end with an inline subroutine to generate the outputs you want.
Or if you can't it will return as either a cell array or a vector and you can pass an anonymous function to generate the desired outputs that way.
Really, can be done many ways. Very contextual.