Wednesday, August 21, 2013

Increment/Decrement Variable (counter)


One problem I had to face in simulink was to implement a incrementacion or decrementation of one variable, and the variable remained updated. (The common expression counter = counter + 1 or counter++ in C).
After some test I found the block 'Matlab Function' the most appropiate to solve this problem.

Fucntion Matlab block
First of all, in order to use this block, a C compiler must be installed in your computer. If you want to know if a C compiler is installed write this expression in Matlab window:
>>mex -setup
The response would be the list of compilers installed in your computer and if Matlab accept them or not.
Furthermore, it gives you this webside: http://www.mathworks.com/support/compilers/R2013a/win64.html.
where a free compiler can be downloaded and installed. This compiler was the one I used and the block works fine.

Data Store Memory block
After that, since I wanted to increment/decrement a variable and this variable must remain updates I found the best solution in global variable block ('Data Store Memory'):
In this block, I had to set the initial value and it is required to set data type and signal type different to auto or complex.

Then, the global variable must be initialized in the fuction block.
Inside the block (double click): Simulink/ Edit Data -> Ports and Data Manager
Then, Add/Data
Name: Name of the global variable
Scope: Data Store Memory

After all that, I was ready to write the code. The code I used was:

function y = fcn(u)
%one input, one output. A increment/decrement depending on u

global A;
if u
A = A+1;
else
A = A-1;
end


y = A;

Note: Output variable must be assigned in all possible cases (recommendation: if is a conditional instruction, always use 'else')

Finally my schematic was like next figure:
Increment/Decrement Variable schematic

The ouput I obtained was:

Increment/Decrement variable output

Note: In order to see the ouput signal like the image above the simulation must be run step by step.


Licencia Creative Commons

6 comments :

  1. Nice job! MatLab/simulink use to be part of my daily job :-). I have several tutorials in my blog about that (I share it down):

    http://www.elblogdejabba.com/2009/04/instalar-matlab-en-ubuntu.html

    Big Kiss Blanquita!! ;-)

    ReplyDelete
  2. this is great. thanks man

    ReplyDelete
  3. Thank you so much!!!!

    ReplyDelete
  4. Global declaration not resolved to a Data Store Memory block registered via the Ports and Data Manager

    ReplyDelete
  5. I was lost in:
    Inside the block (double click): Simulink/ Edit Data

    Thanks for share!

    ReplyDelete