How to make a proc that aply for all variables in maple - maple

for example supposed I want to program a proc that plus 1 to all results that is a real numbers in my program. Is there a way to do that ?

You can use anames('user') to obtain top-level, user-defined variables, and then select those that are real-valued. In the code below, calling incrementReals() will increment all such variables:
restart;
a, b, c := 3, 1 - I, 0.5;
# Procedure to increment by 1 all user-defined variables that are of type 'realcons'.
incrementReals := proc()
local A := select( u -> type( eval(u), 'realcons' ), [ anames( 'user' ) ] ):
local B := map( u -> eval(u) + 1, A ):
assign( A =~ B );
return NULL:
end proc:
# Increment.
incrementReals();
# Confirm that a and b were incremented, but b was not.
'a' = a, 'b' = b, 'c' = c; # a = 4, b = 1 - I, c = 1.5

Related

How do I use value of variable in Maple

How do I get Maple to give the value of a variable in the RHS of an expression, rather than treat it as a variable in an expression. In the following code I want a list of three functions of x which are quadratics with different offsets, but it's not what I get:
ix := [-1,0,1]:
b := []:
for a in ix
do
b := [op(b),x->(x-a)^2];
end do;
and the output is
while I would like it to be (for the last line)
b := [ x -> (x+1)^2, x -> x^2, x -> (x-1)^2 ]
Your problem is that you are trying to use values for a in the construction of the body of a procedure, and not the "RHS of an expression" as you stated.
Try not to use the term "function" in this context, as it just muddles the distinction between expression and procedure.
Here is a way to get the values from ix as replacements for a in a generated list of procedures with (x-a)^2 in the body.
restart;
ix := [-1,0,1]:
b := []:
for a in ix do
b := [op(b), unapply((x-a)^2,x)];
end do:
b;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]
It is inefficient to construct lists in this way, by repeatedly concatenating them. Since that practice scales badly in performance you really ought to drop it as a practice.
You can construct the whole list with one call to seq.
Flist := [ seq( unapply((x-a)^2,x), a in ix ) ]:
Flist;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]
Here, Flist is a list of procedures, each of which can be evaluated at a value by calling it with an argument.
Flist[1];
x -> (x+1)^2
Flist[3](3.4);
5.76
#plot(Flist, -2..2);
Note: Procedures which display with the arrow notation x -> ... are called operators.
For fun, here are equivalents, using expressions,
Elist := [ seq( (x-a)^2, a in ix ) ]:
Elist;
[ 2 2 2]
[(x + 1) , x , (x - 1) ]
Elist[1];
2
(x + 1)
eval(Elist[3], x=3.4);
5.76
#plot(Elist, x=-2..2);
There are other ways to generate the procedures, with values of a in the body being specified programmatically. The unapply command is not the only possible mechanism, although it is the easiest for your example.
Another way is to substitute, for example,
generic := x -> (x-_dummy)^2:
Hlist := [ seq( subs(_dummy=a, eval(generic)), a in ix ) ]:
Hlist;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]

function which return s-tuples with non-negative integers and a given sum $n$

I am trying to write a function which return s-tuples with non-negative integers and a given sum $n$ (the sum of each tuple is $n$). In the program, I need to use s nested loops:
for i1 from 0 to n do
for i2 from 1 to n do
...
for is from 1 to n do
end for;
end for;
end for;
How could I use only a few loops instead of s loops? Thank you very much.
I suggest the combinat:-composition() command. On its own, the command won't include zero terms, but you can instead partition n+s and remove 1 from each term at the end:
restart;
partitions := proc( n :: posint, s :: posint, { allowzero :: truefalse := false } )
local P, u:
if allowzero = false then
P := convert( combinat:-composition( n, s ), 'list' ):
return select( u -> numelems(u) = s, P ):
else
P := procname( n + s, s, ':-allowzero'=false ):
return map( u -> u -~ 1, P ):
end if:
end proc:
partitions( 5, 2, ':-allowzero'=false ); # [ [1,4], [2,3], [3,2], [4,1] ]
partitions( 5, 2, ':-allowzero'=true ); # [ [0,5], [1,4], [2,3], [3,2], [4,1], [5,0] ]

Variable associated to "Optimization terminated successfully" in scipy.optimize.fmin_cg?

I am using scipy.optimize.fmin https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.fmin_cg.html.
What is the variable associated to "Optimization terminated successfully"?
I need it such that I could write something like:
if "optimization not succesful" then "stop the for loop"
Thank you.
Just follow the docs.
You are interested in warnflag (as mentioned by cel in the comments), the 5th element returned, so just index
(0-indexing in python!) the result with result[4] to obtain your value.
The docs also say that some of these are only returned when called with argument full_output=True, so do this.
Simple example:
import numpy as np
args = (2, 3, 7, 8, 9, 10) # parameter values
def f(x, *args):
u, v = x
a, b, c, d, e, f = args
return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f
def gradf(x, *args):
u, v = x
a, b, c, d, e, f = args
gu = 2*a*u + b*v + d # u-component of the gradient
gv = b*u + 2*c*v + e # v-component of the gradient
return np.asarray((gu, gv))
x0 = np.asarray((0, 0)) # Initial guess.
from scipy import optimize
res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args, full_output=True) # full_output !!!
print(res1[4]) # index 4 !!!

Nim operator overloading

Just started programming in the Nim language (which I really like so far). As a learning exercise I am writing a small matrix library. I have a bunch more code, but I'll just show the part that's relevant to this question.
type
Matrix*[T; nrows, ncols: static[int]] = array[0 .. (nrows * ncols - 1), T]
# Get the index in the flattened array corresponding
# to row r and column c in the matrix
proc index(mat: Matrix, r, c: int): int =
result = r * mat.ncols + c
# Return the element at r, c
proc `[]`(mat: Matrix, r, c: int): Matrix.T =
result = mat[mat.index(r, c)]
# Set the element at r, c
proc `[]=`(mat: var Matrix, r, c: int, val: Matrix.T) =
mat[mat.index(r, c)] = val
# Add a value to every element in the matrix
proc `+=`(mat: var Matrix, val: Matrix.T) =
for i in 0 .. mat.high:
mat[i] += val
# Add a value to element at r, c
proc `[]+=`(mat: var Matrix, r, c: int, val: Matrix.T) =
mat[mat.index(r, c)] += val
# A test case
var mat: Matrix[float, 3, 4] # matrix with 3 rows and 4 columns
mat[1, 3] = 7.0
mat += 1.0
# add 8.0 to entry 1, 3 in matrix
`[]+=`(mat, 1, 3, 8.0) # works fine
All this works fine, but I'd like to be able to replace the last line with something like
mat[1, 3] += 4.0
This won't work (wasn't expecting it to either). If I try it, I get
Error: for a 'var' type a variable needs to be passed
How would I create an addition assignment operator that has this behavior? I'm guessing I need something other than a proc to accomplish this.
There are two ways you can do this:
Overload [] for var Matrix and return a var T (This requires the current devel branch of Nim):
proc `[]`(mat: Matrix, r, c: int): Matrix.T =
result = mat[mat.index(r, c)]
proc `[]`(mat: var Matrix, r, c: int): var Matrix.T =
result = mat[mat.index(r, c)]
Make [] a template instead:
template `[]`(mat: Matrix, r, c: int): expr =
mat[mat.index(r, c)]
This causes a problem when mat is not a value, but something more complex:
proc x: Matrix[float, 2, 2] =
echo "x()"
var y = x()[1, 0]
This prints x() twice.

list comprehension without parentheses in a function

I have a function that needs to return the last property of an object that satisfies the condition:
types = {
a: 1,
b: 2,
c: 3
}
g = (s) -> v for k, v of types when k is s
console.log g 'b'
this code prints [ 2 ]
I expected just 2, and not an array. And indeed, this code does print what I expect:
console.log v for k, v of types when k is 'b'
What is wrong?
P.S. I know that instead of this function I can just access the object's property using [], but this is a contrived example.
If we rearrange the code then things should be clearer.
Your second piece of code:
console.log v for k, v of types when k is 'b'
is just another way of writing this:
for k, v of types when k is 'b'
console.log(v)
or even:
for k, v of types
if k is 'b'
console.log(v)
Since there is only one 'b' key, only one console.log call is made.
Your first piece of code:
g = (s) -> v for k, v of types when k is s
is the same as this:
g = (s) ->
a = (v for k, v of types when k is s)
a
The loop, v for k, v of types when k is s yields an array by definition so a will be an array (with only one element) and g will return an array.
console.log v for k, v of types when k is 'b' will call console.log(v) for every v when k satisfies the condition whereas your first code snipped will call console.log(g(b)). If there were two elements in types that satisfied the condition, the outputs would be:
[1, 2]
and
1
2
To make g output the first element that satisfies the condition, you could use return with early out or just take the first element of the results array.
g = (s) -> return v for k, v of types when k is s