Discrete Wavelets

004 - How to Write a Module

Helmut  Knaust - Department of Mathematical Sciences, University of Texas at El Paso, hknaust@utep.edu
10/6/2010; last edit 04/06/2023

SetDirectory[NotebookDirectory[]];
<<DW.m
SetDirectory["Images"]

Variables Inside a Module are Local in Scope

Clear[a,b];
a=7;
fourtimes[a_]:=Module[{b},b=2a;2b]
fourtimes[5]

A module by default returns its last expression.

a

b

From Notebook 031 :

Image processing: Edge detection

pic=Import["Grayscale/benches.png","Data"];
{dimr,dimc}=Dimensions[pic];
ImagePlot[pic]
diff=SparseArray[{{i_,j_}/;i==j->1,{i_,j_}/;i==j+1->-1},{dimc,dimc}];
ve=Abs[pic.diff];
ImagePlot[ve]

Modules

VerticalEdges[pic_]:=Module[
{dimr,dimc,diff},{dimr,dimc}=Dimensions[pic];diff=SparseArray[{{i_,j_}/;i==j->1,{i_,j_}/;i==j+1->-1,{1,dimc}->-1},{dimc,dimc}];Abs[pic.diff]]

ImagePlot[VerticalEdges[pic]]

VerticalEdges2[pic_]:=Module[
{dimr,dimc,diff},{dimr,dimc}=Dimensions[pic];diff=SparseArray[{{i_,j_}/;i==j->1,{i_,j_}/;i==j+1->-1,{1,dimc}->-1},{dimc,dimc}];ImagePlot[Abs[pic.diff]]]

VerticalEdges2[pic]

How to Pass a Function to a Module

Here is a plot of a quadratic function:

Plot[3-2s^2,{s,-2,2}]
Plot[3-2s^2,{s,-2,2},AxesLabel->{s,3-2s^2}]

This does not work:

plot0[f_,y_,start_,end_]:=Module[{},Plot[f[y],{y,start,end}]]

plot0[-2s^2+3,s,-2,2]

First fix: Use a pure function as input.

plot1[f_,start_,end_]:=Module[{},Plot[f[y],{y,start,end},AxesLabel->{f[[1]],f[[2]]}]]

plot1[Function[q,3-2q^2],-2,2]

Here is the fix using a “normal” function:

plot2[f_,y_,start_,end_]:=Module[{Fct},Fct=Function[y,f];Plot[Fct[k],{k,start,end},AxesLabel->{y,f}]]

plot2[-2s^2+3,s,-2,2]

plot2[-2r^2+3,r,-2,2]

Here is the easiest fix using a pure function:

plot3[f_,st_,end_]:=Module[{},Plot[f[t],{t,st,end},AxesLabel->{None,f}]]

plot3[Sin,0,2π]

plot3[Function[r,-2r^2+3],-2,2]

The same with fancier labels for the axes:

plot4[f_,var_,st_,end_]:=Module[{},Plot[f[t],{t,st,end},AxesLabel->{var,f[var]}]]

plot4[Sin,λ,0,2π]

plot4[Function[r,-2r^2+3],κ,-2,2]

TreeForm

TreeForm[Function[s,3s^2-2]]

Function[s,3s^2-2][[1]]