:

## Your favorite and most useful code snippets

Hey Everyone:

I was wondering what are your favorite and most useful code snippets that you often use. Maybe ones that are in your initialization code? Maybe ones that speed up something that you often do in maple? Maybe ones that you've seen on this and other websites and adopted for your own purposes?

For fun, I attach my init.mpl (.txt here, as .mpl attachments are not allowed by mapleprimes) here init.txt

Some of the snippets that I use the most are also listed below:

#rearrange curves inside an already created plot, so that certain curves are "on top" of the other ones.
#discussed here:
#http://www.mapleprimes.com/questions/201626-Order-Of-Curves-In-A-Plot
rearrangeCurves:= proc(
v_items::specfunc(anything, PLOT),
v_reorder::list([integer,integer]):= []
)
local p, curves, rest;
(curves,rest):= selectremove(type, v_items, specfunc(anything, CURVES));
curves:= < op(curves) >:
for p in v_reorder do
curves[p]:= curves[p[[2,1]]]
end do;
PLOT(convert(curves,list)[], op(rest))
end proc:

#for numerical differentiation
#based on the idea from:
#http://www.mapleprimes.com/posts/119554-Data-Interpolation
#example use:
#alist:=[seq(i, i=0..10, 0.1)]:
#data:=map(x->evalf(sin(x)), alist):
#plot(alist, data);
#plot([cos(x), 'num_diff(x, LinearAlgebra:-Transpose(Matrix([alist,data])))'], x=1..10, thickness=5, linestyle=[solid, dot], color=[blue, red]);
num_diff:=proc(x, v_data, v_options:=[method=spline, degree=3])
#v_data is a matrix
#TODO: let the data be in a more arbitrary format that ArrayInterpolation understands, but keep x as first var
evalf(D(x->CurveFitting:-ArrayInterpolation(v_data, [x],v_options[])[])(x));
end:

#extract nth columns/rows from a matrix
#these only work if have a 2d object... should be updated to also work
#with 1d row/column vectors
#Example use cases
#A := LinearAlgebra:-RandomMatrix(20, 20, outputoptions = [datatype = float]);
#nthColumns(A, 2); #Every other column
#nthRows(A, 10)[.., 1..3]; #Every 10th row, but show only first 3 columns
nthColumns:=proc(v_m, v_n)
v_m[..,[seq(i, i=1..rtable_size(v_m), v_n)]]
end:
nthRows:=proc(v_m, v_n)
v_m[[seq(i, i=1..rtable_size(v_m), v_n)],..]
end:

#saves a png plot
savePlot:=proc(v_p, v_fileName, v_w:="800", v_h:="500")
plotsetup("png", plotoutput=v_fileName, plotoptions=cat("quality=100,portrait,noborder,width=",v_w,",height=",v_h));
print(plots[display](v_p)); 