Wednesday, February 5, 2014

Trigger a Matlab function with another Matlab function


Thank you for your question, Mahmoud Hasanloo. I found a solution to your problem I hope helps you. First of all, the problem is that there is a subsystem which generates a condition, that condition is read by a matlab function. The occurrence of that condition is detected by another Matlab function, and it is needed to related both Matlab functions.

The first thing that comes to my mind is that you can join the two Matlab function codes into one, so the occurrence of the condition is detected and the the condition could be executed.

Another solution could be to add a global variable as a flag to initialized the second Matlab function.

The last solution and the one I will explain deeply is to use the output of one Matlab function as the input of the second one. I propose you the next example solution:

I created a subsystem that generates a Random Integer between 0-4.
Random Integer Subsystem
Random Number Source
Random Integer Scope

Now, the occurrence of the condition that is read by a Matlab function is that the random integer generated is greater than 1 or not. In the case the occurrence is true, the condition in the second Matlab function will be executed.

function y = fcn(u)
% If input is >1, output will be true (1), otherwise output will be false (0)

if u > 1
    y = 1;
else
    y = 0;
end
Output =1 if input is greater than one, Output = 0 if not
Finally, the condition that is executed in the second Matlab function is that if the occurrence is true, the output will be the sumation of all past integers generated, and if the occurrence is false, the output will be reset. In order to do this sumatory, global variables are used.

Note: The integer could be saved in a global variable or could be inserted in Matlab function directly as an input variable. Sum is needed to be a global variable.

function y = fcn(u)
% If input is 1, output will the sum of the array, otherwise output will be
% 0.

global I;
global sum;

sum = sum + I;
if u 
    y = sum;
else
    sum = 0;
    y = 0;
end


Sumatory of the integers until output is reset
The overall system is the next one:
Total system
I hope this helps to solve your problem. If there is something I undertood in a wrong way or you have any further questions do not hesitate in asking me, please. Thank you for your collaboration.


Licencia Creative Commons