Recursive definition of a vector - function

I would like to define a list using a for loop and I need to do it using a function of the n-iterate.
I have:
Initialization
In[176]: Subscript[y, 0] = {1, 2, 3}
Out[180]: {1,2,3}
The function:
In[181]: F[n_] := For[l = 1, l++, l <= 3, Subscript[y, n + 1][[l]] :=Subscript[y, n][[l]]+ n]
I call the function
F[0]
and I get:
In[183]: Subscript[y, 1]
Out[183]: Subscript[0, 1]
I should have {1,2,3}.
Anyone know why it isn't working as it should?

I have troubles recreating your error, problem.
I understand you want to add n to your vector, where n is the number of the subscript.
Here's another way to have a go at your question, avoiding the loop and the subscripts:
Clear#y;
y[0] = {1, 2, 3};
y[n_Integer] : =y[n - 1] + n
(as Plus is Listable, you can just add n to the vector, avoiding the For)
and then call it using, e.g.
y[0]
{1,2,3}
or
y[5]
{16,17,18}
Alternatively, using memoization, you could define y as follows:
y[n_Integer] := y[n] = y[n - 1] + n
This will then store already calculated values (check ?y after executing e.g. y[5]). Don't forget to Clear y, if y changes.
Obviously, for a function as this one, you might want to consider:
y[n_Integer] := y[0] + Total[Range[n]]

Related

SWI-Prolog: Generalize a predicate to calcluate the power of some function

I want to generalize some predicate written in swi-prolog to calculate the power of some function. My predicate so far is:
% calculates the +Power and the +Argument of some function +Function with value +Value.
calc_power(Value, Argument, Function, Power) :-
not(Power is 0),
Power is Power_m1 + 1,
Value =..[Function, Buffer],
calc_power(Buffer, Argument, Function, Power_m1), !.
calc_power(Argument, Argument, _, 0).
The call calc_power((g(a)),A,f,POW). gives so far:
A = g(a),
POW = 0.
My generalization should also solve calls like that:
calc_power(A1, a, f, 3).
the solution should be in that special calse A1 = f(f(f(a))). But for some reason it doesn't work. I get the error:
ERROR: Arguments are not sufficiently instantiated
in line
Power is Power_m1 + 1
it means probably in swi prolog it is not possible to take plus with two variables. How can I solve this problem?
Can delay the + 1 operation with:
int_succ(I0, I1) :-
( nonvar(I0) ->
integer(I0),
I0 >= 0,
I1 is I0 + 1
; nonvar(I1) ->
integer(I1),
I1 >= 1,
I0 is I1 - 1
; when((nonvar(I0) ; nonvar(I1)), int_succ(I0, I1))
).
Example in swi-prolog:
?- int_succ(I0, I1), I1 = 7.
I0 = 6,
I1 = 7.
This is more flexible than https://www.swi-prolog.org/pldoc/man?predicate=succ/2 , and can of course be modified to support negative numbers if desired.
Found some solution
:- use_module(library(clpfd)).
% calculates the +Power and the +Argument of some function +Function with value +Value.
calc_power(Argument, Argument, _, 0).
calc_power(Value, Argument, Function, Power) :-
Power #\= 0,
Power #= Power_m1 + 1,
Value =..[Function, Buffer],
calc_power(Buffer, Argument, Function, Power_m1).

Solving a system of equations in Maple

I have a system of n equations and n unknown variables under symbol sum. I want to create a loop to solve this system of equations when inputting n.
y := s -> 1/6cos(3s);
A := (k, s) -> piecewise(k <> 0, 1/2exp(ksI)/abs(k), k = 0, ln(2)exp(s0I) - sin(s));
s := (j, n) -> 2jPi/(2*n + 1);
n := 1;
for j from -n to n do
eqn[j] := sum((A(k, s(j, n))) . (a[k]), k = -n .. n) = y(s(j, n));
end do;
eqs := seq(eqn[i], i = -n .. n);
solve({eqs}, {a[i]});
enter image description here
Please help me out!
I added some missing multiplication symbols to your plaintext code, to reproduce it.
restart;
y:=s->1/6*cos(3*s):
A:=(k,s)->piecewise(k<>0,1/2*exp(k*s*I)/abs(k),
k=0,ln(2)*exp(s*I*0)-sin(s)):
s:=(j,n)->2*j*Pi/(2*n+1):
n:=1:
for j from -n to n do
eqn[j]:=add((A(k,s(j,n)))*a[k],k=-n..n)=y(s(j,n));
end do:
eqs:=seq(eqn[i],i=-n..n);
(-1/4+1/4*I*3^(1/2))*a[-1]+(ln(2)+1/2*3^(1/2))*a[0]+(-1/4-1/4*I*3^(1/2))*a[1] = 1/6,
1/2*a[-1]+ln(2)*a[0]+1/2*a[1] = 1/6,
(-1/4-1/4*I*3^(1/2))*a[-1]+(ln(2)-1/2*3^(1/2))*a[0]+(-1/4+1/4*I*3^(1/2))*a[1] = 1/6
You can pass the set of names (for which to solve) as an optional argument. But that has to contain the actual names, and not just the abstract placeholder a[i] as you tried it.
solve({eqs},{seq(a[i],i=-n..n)});
{a[-1] = 1/6*I/ln(2),
a[0] = 1/6/ln(2),
a[1] = -1/6*I/ln(2)}
You could also omit the indeterminate names here, as optional argument to solve (since you wish to solve for all of them, and no other names are present).
solve({eqs});
{a[-1] = 1/6*I/ln(2),
a[0] = 1/6/ln(2),
a[1] = -1/6*I/ln(2)}
For n:=3 and n:=4 it helps solve to get a result quicker here if exp calls are turned into trig calls. Ie,
solve(evalc({eqs}),{seq(a[i],i=-n..n)});
If n is higher than 4 you might have to wait long for an exact (symbolic) result. But even at n:=10 a floating-point result was fast for me. That is, calling fsolve instead of solve.
fsolve({eqs},{seq(a[i],i=-n..n)});
But even that might be unnecessary, as it seems that the following is a solution for n>=3. Here all the variables are set to zero, except a[-3] and a[3] which are both set to 1/2.
cand:={seq(a[i]=0,i=-n..-4),seq(a[i]=0,i=-2..2),
seq(a[i]=0,i=4..n),seq(a[i]=1/2,i=[-3,3])}:
simplify(eval((rhs-lhs)~({eqs}),cand));
{0}

Octave Get function_handle from vectorfunction with constants

I've tried to get a vectorfunction like
syms x
fn=function_handle([x^2;1])
Output is #(x) [x.^2;1]
Thats leads of course in an error while calling fn with vectorarguments
(Dimensions mismatch)
Is there a way to avoid the issue?
I've tried fn=function_handle([x^2;1+0*x])
but the codeoptimation - or whatever - deletes the 0*x - term.
Any suggestions?
If you think about it, what function_handle does here is reasonable, since the scenario you require here cannot be reliably predicted in advance. So I don't think there is an obvious option to change its behaviour.
You could deal with this in a couple of ways.
One way is to treat the function handle as unvectorised, and rely on external vectorization, e.g.
f = function_handle([x^2; 1]);
[arrayfun( f, [1,2,3,4,5], 'uniformoutput', false ){:}]
Alternatively, you could introduce a symbolic helper constant c, and call f appropriately. You can also create a wrapper function that uses an appropriate default constant. Examples:
f = function_handle([x^2; c], 'vars', [x,c]);
f( [1,2,3,4,5], [1,1,1,1,1] )
g = #(x) f( x, ones(size(x)) );
g([1,2,3,4,5])
or
f = function_handle([x^2; (x+c)/x], 'vars', [x,c]);
f([1,2,3,4,5], 0)
g = #(x) f( x, 0 )
g([1,2,3,4,5])
Thank you.
Today, i'm happy of a solution i've found.
I turn the arrayfcn into a cellfcn:
f_h_Cell=#(x, y) {x .* y, 0}
nf = #(x) #mifCell2Mat (f_h_Cell (x (size (x) (1) * 0 / 2 + 1:size (x) (1) * 1 / 2,{':'} (ones (1, ndims (x) - 1)){:}), x (size (x) (1) * 1 / 2 + 1:size (x) (1) * 2 / 2, {':'} (ones (1, ndims (x) - 1)) {:})))
and then:
function res=mifCell2Mat(resCell)
resCell=transpose(resCell);
[~,idx]=max(cellfun(#numel,resCell));
refSize=(size(resCell{idx}));
resCell=cellfun(#(x) x+zeros(refSize),resCell,'uniformoutput',false);
res=cell2mat(resCell);
endfunction
All automate calling following function
f=fcn(name,domain,parms,fcn);
so a simple f.nf([x;y;z]) call gives the result.
Of course it doesn't work, if there are numel's between 1 and say size=[10,10] of
eg size=[10,1], but so what ... In most cases it work's for me (until now: allways).
Oh, while i read my code just here, i've found a little bug:
refSize=(size(resCell{idx}));
must of course change to
refSize=(size(resCell{idx(1)}));
cause there a possible more than one max sizes in the idx, so i've picked the first. I do first a test of constant outDims, so that these workaround only occours, if there are constants. In the other cases (if all outDims contain domainvars) a simple anonymous function of a matrix-handle appears to the user:
f_h_Mat=#(x, y) [x .* y; x]
nf=#(x) f_h_Mat (x (size (x) (1) * 0 / 2 + 1:size (x) (1) * 1 / 2, {':'} (ones (1, ndims (x) - 1)) {:}), x (size
(x) (1) * 1 / 2 + 1:size (x) (1) * 2 / 2, {':'} (ones (1, ndims (x) - 1)) {:}))

Defining Your Own Functions with a few procedures in Wolfram Language

I have created a function with one procedure....
Func1[n_] := Table[a[i], {i, n}]
which returns
Func1[5]
{a[1], a[2], a[3], a[4], a[5]}
I also have created a function with a few parameters or with a few arguments, few variables!
Func1[x_, y_, z_] := (x + y)*z - 1
which returns
Func1[5, 2, 3]
20
But what about if I want to create a function with a several procedure which returns whatever I want?
I already know that when one procedure is done I have to type " ; " at the end of this procedure!
Like in for loops we do....
For[k = 2, k < 3, k++,
S := Table[a[i], {i, n}];
B := Dimensions[S][[1]]];
]
So I need to create a function with a several procedure!
How to do it?
Please help me!
A couple of examples here. Remember to use lower-case initial letters to avoid conflicting with built-in functions which all start with a capital letter.
s[n_] := Table[a[i], {i, n}]
b[s_] := Dimensions[s][[1]]
For[k = 2, k < 3, k++,
x = s[k];
Print[b[x]]]
2
For[k = 2, k < 3, k++,
Print[b[s[k]]]]
2
Use parentheses for grouping.
For example
set$s$b[n_Integer] := ($s = Table[a[i], {i, n}];
$b = Dimensions[$s][[1]];)
Now, after executing, e.g.,
set$s$b[5]
one will get
$s
{a[1], a[2], a[3], a[4], a[5]}
$b
5
However, making use of modularity might be a better design choice in situations where the execution of several procedures is needed.

How can you emulate recursion with a stack?

I've heard that any recursive algorithm can always be expressed by using a stack. Recently, I've been working on programs in an environment with a prohibitively small available call stack size.
I need to do some deep recursion, so I was wondering how you could rework any recursive algorithm to use an explicit stack.
For example, let's suppose I have a recursive function like this
function f(n, i) {
if n <= i return n
if n % i = 0 return f(n / i, i)
return f(n, i + 1)
}
how could I write it with a stack instead? Is there a simple process I can follow to convert any recursive function into a stack-based one?
If you understand how a function call affects the process stack, you can understand how to do it yourself.
When you call a function, some data are written on the stack including the arguments. The function reads these arguments, does whatever with them and places the result on the stack. You can do the exact same thing. Your example in particular doesn't need a stack so if I convert that to one that uses stack it may look a bit silly, so I'm going to give you the fibonacci example:
fib(n)
if n < 2 return n
return fib(n-1) + fib(n-2)
function fib(n, i)
stack.empty()
stack.push(<is_arg, n>)
while (!stack.size() > 2 || stack.top().is_arg)
<isarg, argn> = stack.pop()
if (isarg)
if (argn < 2)
stack.push(<is_result, argn>)
else
stack.push(<is_arg, argn-1>)
stack.push(<is_arg, argn-2>)
else
<isarg_prev, argn_prev> = stack.pop()
if (isarg_prev)
stack.push(<is_result, argn>)
stack.push(<is_arg, argn_prev>)
else
stack.push(<is_result, argn+argn_prev>)
return stack.top().argn
Explanation: every time you take an item from the stack, you need to check whether it needs to be expanded or not. If so, push appropriate arguments on the stack, if not, let it merge with previous results. In the case of fibonacci, once fib(n-2) is computed (and is available at top of stack), n-1 is retrieved (one after top of stack), result of fib(n-2) is pushed under it, and then fib(n-1) is expanded and computed. If the top two elements of the stack were both results, of course, you just add them and push to stack.
If you'd like to see how your own function would look like, here it is:
function f(n, i)
stack.empty()
stack.push(n)
stack.push(i)
while (!stack.is_empty())
argi = stack.pop()
argn = stack.pop()
if argn <= argi
result = argn
else if n % i = 0
stack.push(n / i)
stack.push(i)
else
stack.push(n)
stack.push(i + 1)
return result
You can convert your code to use a stack like follows:
stack.push(n)
stack.push(i)
while(stack.notEmpty)
i = stack.pop()
n = stack.pop()
if (n <= i) {
return n
} else if (n % i = 0) {
stack.push(n / i)
stack.push(i)
} else {
stack.push(n)
stack.push(i+1)
}
}
Note: I didn't test this, so it may contain errors, but it gives you the idea.
Your particular example is tail-recursive, so with a properly optimising compiler, it should not consume any stack depth at all, as it is equivalent to a simple loop. To be clear: this example does not require a stack at all.
Both your example and the fibonacci function can be rewritten iteratively without using stack.
Here's an example where the stack is required, Ackermann function:
def ack(m, n):
assert m >= 0 and n >= 0
if m == 0: return n + 1
if n == 0: return ack(m - 1, 1)
return ack(m - 1, ack(m, n - 1))
Eliminating recursion:
def ack_iter(m, n):
stack = []
push = stack.append
pop = stack.pop
RETURN_VALUE, CALL_FUNCTION, NESTED = -1, -2, -3
push(m) # push function arguments
push(n)
push(CALL_FUNCTION) # push address
while stack: # not empty
address = pop()
if address is CALL_FUNCTION:
n = pop() # pop function arguments
m = pop()
if m == 0: # return n + 1
push(n+1) # push returned value
push(RETURN_VALUE)
elif n == 0: # return ack(m - 1, 1)
push(m-1)
push(1)
push(CALL_FUNCTION)
else: # begin: return ack(m - 1, ack(m, n - 1))
push(m-1) # save local value
push(NESTED) # save address to return
push(m)
push(n-1)
push(CALL_FUNCTION)
elif address is NESTED: # end: return ack(m - 1, ack(m, n - 1))
# old (m - 1) is already on the stack
push(value) # use returned value from the most recent call
push(CALL_FUNCTION)
elif address is RETURN_VALUE:
value = pop() # pop returned value
else:
assert 0, (address, stack)
return value
Note it is not necessary here to put CALL_FUNCTION, RETURN_VALUE labels and value on the stack.
Example
print(ack(2, 4)) # -> 11
print(ack_iter(2, 4))
assert all(ack(m, n) == ack_iter(m, n) for m in range(4) for n in range(6))
print(ack_iter(3, 4)) # -> 125