Anonymous function handle incosistence problem with Fourier functions
7 views (last 30 days)
Show older comments
Hello, during some optics simulation I dared to shorten my code (a .m type) by making fourier transform an anonymous function as such:
F = @(x) fftshift(fft(ifftshift(x)));
iF = @(x) ifftshift(ifft(fftshift(x)));
poow = @(x) abs(x).^ 2;
with these I would Transform, inverse transform and Find the intensity of the signal but for a reason I don't know it only works when I post it in the command window... sometimes.
here is an example of it in action:
L = 15; % mm
F = 100; % mm
f0 = 1/100e-3; % lp/mm
f1 = 1/300e-3; % lp/mm
dx = 4e-3; % mm
t = 0:dx:L-dx; % mm
n = length(t);
f = -1/(2*dx):1/L:(1/(2*dx)-1/L);
object = chirp(t,f0,t(end),f1,"quadratic");
I = poow(object);
%% transform the object and display
object_ = F(object);
I_object_ = poow(object_);
Now, the problem is as you might see here is that the error this time is:
Array indices must be positive integers or logical values.
but on my machine its:
Error: File: LiveEditorEvaluationHelperE1735339498.m Line: 57 Column: 7
Invalid expression. Check for missing or extra characters.
Error in LiveEditorEvaluationHelperE1735339498>@(x)fftshift(fft(ifftshift(x))) (line 3)
F = @(x) fftshift(fft(ifftshift(x)));
^
this error happens to all previewed anonymous functions.
I have checked if a simpler handle would work and it does only crash when calling these 3 specific ones when running the script.
1 Comment
Stephen23
on 24 Jul 2025
Edited: Stephen23
on 24 Jul 2025
"Array indices must be positive integers or logical values."
is caused by these two lines:
F = 100; % mm
..
object_ = F(object);
where you incorrectly think that you are calling a function, but in fact you are indexing into a scalar numeric.
To debug the other error message please upload your code by clicking the paperclip button. Did you copy that code from a website or something similar?
Answers (1)
Matt J
on 24 Jul 2025
Edited: Matt J
on 24 Jul 2025
Aside from what Stephen mentions,
(1) the time and frequency axes need to have a common origin at the center of the array.
(2) ifftshift always comes first, in both F and iF, when processing centered signals.
F = @(x) fftshift(fft(ifftshift(x)));
iF = @(x) fftshift(ifft(ifftshift(x)));
poow = @(x) abs(x).^ 2;
L = 15; % mm
%F = 100; % mm
f0 = 1/100e-3; % lp/mm
f1 = 1/300e-3; % lp/mm
dx = 4e-3; % mm
%Set up axes
n=ceil(2*L/dx);
df=1/n/dx;
ax=-ceil((n-1)/2):+floor((n-1)/2); %normalized axis
t=ax*dx; %time axis
f=ax*df; %frequency axis
object=zeros(size(t));
object(t>=0) = chirp(t(t>=0),f0,t(end),f1,"quadratic");
I = poow(object);
%% transform the object and display
object_ = F(object);
I_object_ = poow(object_);
figure; plot(t,object);
figure; plot(f,abs(object_))
0 Comments
See Also
Categories
Find more on Fourier Analysis and Filtering in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

