Search code examples
scilabxcos

How to define persistent matrix variable inside the Scilab function?


I have been developing a Scilab function where I need to have persistent variable of the matrix type. Based on my similar question I have chosen the same approach. Below is the code I have used for test of this approach.

function [u] = FuncXYZ(x)

global A;
global init;

if init == 0 then
   init = 1;
   A = eye(4, 4);
endif

u = A(1, 1);

endfunction

As soon as I have integrated the function inside my Xcos simulation I have been surprised that I see "0" at the output of the scifunc_block_m.

Nevertheless I have found that in case I use below given command for "return" from the function

u = A(3, 3);

the function returns really the expected "1". Additionaly if I take a look at the Variable Browser on the top right corner of the Scilab window I can't se the expected A 4x4 item. It seems that I am doing something wrong.

Can anybody give me an advice how to define a persistent variable of the matrix type inside the Scilab function? Thanks in advance for any ideas.


Solution

  • Global variables are by default initialized with an empty matrix. Hence, you should detect first call with isempty()

    function [u] = FuncXYZ(x)
      global A;
      global init;
      if isempty(init)
        init = 1;
        A = eye(4, 4);
      end
      u = A(1, 1);
    endfunction
    

    BTW, your code is incorrect, there is no endif in Scilab.