# Function of symbolic array elements

I want to create a function like this:

def f(A,B):
return [A[1]*B[1],A[0],B[2]]


However, the thing that the function is supposed to return is calculated in an earlier part of the program. Since Sagemath has a problem with symbolic indices, I have previously defined A and B as follows:

Nf=5
B =[0 for j in range(Nf+1)]
A =[0 for j in range(Nf+1)]
for j in range(Nf+1):
A[j]=var('a_'+str(j))
B[j]=var('b_'+str(j))


The thing that the function should return is calculated in another part of the program. Suppose that it is something like this (evaluated from a separate subroutine):

temp=[a_1*b_1, a_0, b_2]


So my question is: how do I turn this temp into a function similar to f, and the second question: the matrix element references are replaced by variable names. Even if I define a function for temp as it is, I will have to define a huge number of input variables f(a_1, b_1, a_0, b_2, ...) for the function whereas if I could just replace the variables a_1 with A[1], etc., this would have enabled me to use f(A,B) making the function definition so much more compact. How can I achieve this?

edit retag close merge delete

Sort by » oldest newest most voted

First of all, you can condense your code a little bit by writing

A=[SR.var('a_'+str(j)) for j in range(Nf+1)]


etc. With this version you do not have the side-effect of a_0 being bound, so your only way of spelling the variable name is A[0].

If you just write

def temp(A,B):
return [A[1]*B[1],A[0],B[2]]


you have what you describe.

Perhaps you mean that you have a symbolic expression S in the variable occurring in A,B and you want to substitute values for them; say lists a,b and you want to make the substitutions A[0]=a[0], A[1]=a[1] etc. It should be possible to do the following

def evaluate_at(S,a,b):
return S(dict(zip(A,a)+zip(B,b)))


In that case, with

L=[A[1]*B[1],A[0],B[2]]


your function temp should probably be

def temp(a,b):
return [evaluate_at(S,a,b) for S in L]

more

Thank you. Your solution works! With this new method of writing if I have L in either variable type format L=[a_1*b_1, a_0, b_2] or in list indexed format L=[A[1]*B[1],A[0],B[2]] I still get a working function when I type temp(A,B) and there is no need to write out the variables inside each of the lists as the function argument. Of course for the former case, the variables a_0, a_1, a_2 should have be defined somewhere via a_0=var('a_0') or using the non-compact list definition that I used previously. You are a master! Thanks! Just a question, can you explain to me how dict and zip work?

( 2018-09-17 04:34:50 -0500 )edit
1

dict and zip are standard python functions, which you can look up in the python documentation.

( 2018-09-17 12:48:20 -0500 )edit