Related
I'm having a hard time doing an animation with Julia.
I have a function sf(t)=t^(1/2) going from tmin=0 to tmax=40, and I don't understand how to show the solution progressively from tmin to tmax. I have tried multiple approaches using the Julia docs and tutos I found online but they almost all use predefined functions (mainly sin and cos). The error Julia returns with the code below is MethodError: no method matching getindex(::typeof(sf), ::Int64). I have two questions: Why is this error appearing? and Is Ithere a simpler way to create an animation than to access indices in a loop?
Thanks
using Plots
tmin=0
tmax=40
tvec= range(tmin,tmax,length=100)
# I define the function here, but I'm not sure this is really needed
function sf(t)
t^(1/2)
end
# I create an "empty" plot to use it in animation
p=plot(sf,0)
# To create the animation, I do a loop over all t's present in tvec
anim = #animate for i ∈ 0:length(tvec)-1
push!(p,tvec(i),sf(i))
frame(anim)
end
# And finally I (try to) display the result
gif(anim,"scale_factor.gif",fps=30)
IIRC the #animate or #gif macro expects a plot at the end of the loop, so you want to do something like this:
anim = #animate for i ∈ eachindex(tvec)
plot(sf, tvec[begin:i])
end
gif(anim,"scale_factor.gif",fps=30)
I tend to write some codes in GAMS that include a loop that exclude some indices ,how can I write some a loop like with exception?
u("p1","j1")*o1("p1","j2") - sum(t,v("p1","j1",t)*I1("p1","j2",t))=l=0;
u("p1","j1")*o1("p1","j3") - sum(t,v("p1","j1",t)*I1("p1","j3",t))=l=0;
in these equations u , o together and also v,I1 together have different indices j;
how can write this loop?
You can use a loop, but probably a better solution is to limit the equations to the right combination of sets. In any case it can be done using alias of the sets and the SameAs operator.
Alias(p,pp);
Alias(j,jj);
E_myEquation(p,j,pp,jj) $(not (SameAs(p,pp) and SameAs(j,jj)))..
u(p,j)*o1(pp,jj) - sum(t, v(p,j,t)*I1(pp,jj,t)) =l= 0;
This defines the equation for all combinations of (p,j) with itself, except for (p,j)==(p,j).
I hope I have understood the request correctly, but otherwise you can probably figure out the exact implementation you want, using the Alias and SameAs functions.
Is there an equivalent to numpy's apply_along_axis() (or R's apply())in Julia? I've got a 3D array and I would like to apply a custom function to each pair of co-ordinates of dimensions 1 and 2. The results should be in a 2D array.
Obviously, I could do two nested for loops iterating over the first and second dimension and then reshape, but I'm worried about performance.
This Example produces the output I desire (I am aware this is slightly pointless for sum(). It's just a dummy here:
test = reshape(collect(1:250), 5, 10, 5)
a=[]
for(i in 1:5)
for(j in 1:10)
push!(a,sum(test[i,j,:]))
end
end
println(reshape(a, 5,10))
Any suggestions for a faster version?
Cheers
Julia has the mapslices function which should do exactly what you want. But keep in mind that Julia is different from other languages you might know: library functions are not necessarily faster than your own code, because they may be written to a level of generality higher than what you actually need, and in Julia loops are fast. So it's quite likely that just writing out the loops will be faster.
That said, a couple of tips:
Read the performance tips section of the manual. From that you'd learn to put everything in a function, and to not use untyped arrays like a = [].
The slice or sub function can avoid making a copy of the data.
How about
f = sum # your function here
Int[f(test[i, j, :]) for i in 1:5, j in 1:10]
The last line is a two-dimensional array comprehension.
The Int in front is to guarantee the type of the elements; this should not be necessary if the comprehension is inside a function.
Note that you should (almost) never use untyped (Any) arrays, like your a = [], since this will be slow. You can write a = Int[] instead to create an empty array of Ints.
EDIT: Note that in Julia, loops are fast. The need for creating functions like that in Python and R comes from the inherent slowness of loops in those languages. In Julia it's much more common to just write out the loop.
In lisp there is syntax to execute several expressions in sequence within function arguments. Given R's lispy origins, I'm wondering is there an equivalent feature in R? I'm imagining writing something like the following:
with(heat,
do(qqnorm(loss), qqline(loss)))
In R, brackets are used to group multiple statements in a "compound statement", which appears to be the role played by progn in Lisp. As with progn, all of the component statements are evaluated, but only the value of the final statement is returned.
with(mtcars,
{qqnorm(mpg); qqline(mpg)})
This question already has answers here:
Can every recursion be converted into iteration?
(18 answers)
Closed 2 years ago.
As far as I know, most recursive functions can be rewritten using loops. Some may be harder than others, but most of them can be rewritten.
Under which conditions does it become impossible to rewrite a recursive function using a loop (if such conditions exist)?
When you use a function recursively, the compiler takes care of stack management for you, which is what makes recursion possible. Anything you can do recursively, you can do by managing a stack yourself (for indirect recursion, you just have to make sure your different functions share that stack).
So, no, there is nothing that can be done with recursion and that cannot be done with a loop and a stack.
Any recursive function can be made to iterate (into a loop) but you need to use a stack yourself to keep the state.
Normally, tail recursion is easy to convert into a loop:
A(x) {
if x<0 return 0;
return something(x) + A(x-1)
}
Can be translated into:
A(x) {
temp = 0;
for i in 0..x {
temp = temp + something(i);
}
return temp;
}
Other kinds of recursion that can be translated into tail recursion are also easy to change. The other require more work.
The following:
treeSum(tree) {
if tree=nil then 0
else tree.value + treeSum(tree.left) + treeSum(tree.right);
}
Is not that easy to translate. You can remove one piece of the recursion, but the other one is not possible without a structure to hold the state.
treeSum(tree) {
walk = tree;
temp = 0;
while walk != nil {
temp = temp + walk.value + treeSum(walk.right);
walk = walk.left;
}
}
Every recursive function can be implemented with a single loop.
Just think what a processor does, it executes instructions in a single loop.
I don't know about examples where recursive functions cannot be converted to an iterative version, but impractical or extremely inefficient examples are:
tree traversal
fast Fourier
quicksorts (and some others iirc)
Basically, anything where you have to start keeping track of boundless potential states.
It's not so much a matter of that they can't be implemented using loops, it's the fact that the way the recursive algorithm works, it's much clearer and more concise (and in many cases mathematically provable) that a function is correct.
Many recursive functions can be written to be tail loop recursive, which can be optimised to a loop, but this is dependent on both the algorithm and the language used.
They all can be written as an iterative loop (but some might still need a stack to keep previous state for later iterations).
One example which would be extremely difficult to convert from recursive to iterative would be the Ackermann function.
Indirect recursion is still possible to convert to a non-recursive loop; just start with one of the functions, and inline the calls to the others until you have a directly recursive function, which can then be translated to a loop that uses a stack structure.
In SICP, the authors challenge the reader to come up with a purely iterative method of implementing the 'counting change' problem (here's an example one from Project Euler).
But the strict answer to your question was already given - loops and stacks can implement any recursion.
You can always use a loop, but you may have to create more data structure (e.g. simulate a stack).