0
$\begingroup$

I'd like to do some tedious calculations. The toy model is something like:

n = 3;
phaseList = ToExpression /@ StringTemplate["phase``"] /@ Range[n];

Abs[#]^2 &@
 Fourier[Exp[I*phaseList] /. MapThread[Rule, {phaseList, Range@n}]]

The output should be (* {1.44297, 0.33185, 1.22518} *)

However, when the calculations go more complicated, it would be convenient to do like this,

Abs[#]^2 &@
     Fourier[Exp[I*phaseList]]+phaseList/.MapThread[Rule, {phaseList, Range@n}]

Now, a warning appears,

Fourier::fftl: Argument {E^(I phase1),E^(I phase2),E^(I phase3),E^(I phase4),E^(I phase5)} is not a non-empty list or rectangular array of numeric quantities.

so my first question is, how to avoid this warning?

Actually, This complicated calculation would be the formula used in NMinimize,

NMinimize[Abs[#]^2 &@
         Fourier[Exp[I*phaseList]]+phaseList,phaseList]

To suppress any error, this can be used in this way,according to this post

NMinimize[Hold@Abs[#]^2 &@
             Fourier[Exp[I*phaseList]]+phaseList,phaseList]

But I really cannot figure out how it works.

So my second question is, why the Hold here should be presented.

Thank you for your help.

$\endgroup$
1
  • $\begingroup$ Abs[#]^2 &@list can be written more succinctly as Abs@list^2 $\endgroup$
    – Bob Hanlon
    Jan 20, 2017 at 14:25

1 Answer 1

4
$\begingroup$

First of all I recommend using indexed objects for phaseList:

phaseList = Array[phase, 3];

Abs[#]^2 &@Fourier[Exp[I*phaseList] /. phase[x_] :> x]
{1.44297, 0.33185, 1.22518}

You get the error because Fourier is evaluated before phaseList expressions are replaced with numeric values, just as the warning message says. You avoid it by preventing that evaluation, or simply Quiet it as it doesn't prevent later evaluation as you intend.

Abs[#]^2 &@Hold[Fourier][Exp[I*phaseList]] + phaseList /. 
  phase[x_] :> x // ReleaseHold

Block[{Fourier},
  Abs[#]^2 &@Fourier[Exp[I*phaseList]] + phaseList /. phase[x_] :> x
]

Quiet[
  Abs[#]^2 &@Fourier[Exp[I*phaseList]] + phaseList /. phase[x_] :> x,
  Fourier::fftl
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.