Search code examples
scilab

Building a function by another function scilab


I need to build a function that can build other functions in Scilab. I will try to explain with an example.

//A1 and A2 g12 are functions from R^2->R^2
// Here is what I can do. 
deff('[Xprime]=Sys2(t,X)','Xprime=[A1(t,X(1:2)),A2(t,X(3:4))+g2(t,X(1:2),X(3:4))]')

Now, I do not know how many functions A1, A2, .... An there will be. So I need to store them in a list.

l1 = list(); l2 = list();
l1.($+1) = A1; l1.($+1) = A2; l1.($+1) = A3; ...
l2.($+1) = g1; l2.($+1) = g2; l2.($+1) = g3; ...

I want to implement a function like this:

function Xprime=Sys(l1, l2)
       //... I do not know what to type ...
endfunction 

This function would output:

deff('[Xprime]=Sys2(t,X)','Xprime=[A1(t,X(1:2))+g1(t,X(1:2)),A2(t,X(3:4))+g2(t,X(3:4)), ...]')

I hope It is understandable.


Solution

  • I wrote a short setup which might be helpfull. It's not fully functional right now but it will probably give you some idea how to achieve your goal.

    funcprot(0) //Mute warnings about functions definitions
    
    function [Xprime_header, Xprime_body]=Sys(l1, l2)
    
    Xprime_header = '[Xprime]=Sys2(t,X)'
    
    // Add the beginning of the body
    Xprime_body = "Xprime=["
    
    count = length(l1)
    
    // Add each argument
    for i = 1:count        
        Xprime_body = Xprime_body + string( l1(i) ) + "(t,X(" + string(i) + "," + string(i+1) + "))"  
    
        Xprime_body = Xprime_body + "+" + string( l2(i) )  + "(t,X(" + string(i) + "," + string(i+1) + "))"
    
        if( i < count )            
            Xprime_body = Xprime_body + ","
        end              
    end
    
    // Add the last part
    Xprime_body = Xprime_body + ',X(' + string(count-1) + ":" + string(count) + ")]"
    
    endfunction 
    
    l1 = list(); l2 = list();
    l1($+1) = 'A1'; l1($+1) = 'A2'; l1($+1) = 'A3'; 
    l2($+1) = 'g1'; l2($+1) = 'g2'; l2($+1) = 'g3'; 
    
    [ Xprime_header, Xprime_body ] = Sys( l1, l2)
    
    disp( Xprime_body )
    
    // Deff your function here, so it is in the main scope
    deff( Xprime_header, Xprime_body)