I started learning a little Matlab a couple days ago.
I wanted to plot a Dirac-comb-like approximation, so given that I knew some functional programming, and that I have been told “you shouldn’t need for loops in Matlab”, I ended up with this:
M = 50
dx = 0.1
r = 20
x = -r/dx:r/dx
y = arrayfun(@(k) dx .* sum(exp(-2j * pi * dx * k * (-M:dx:M))), x)
But I feel arrayfun isn’t a good way to do this — it just feels awkward/overkill in Matlab.
Or maybe it’s just me, I don’t know.
Is there a better way to plotting this graph without resorting to arrayfun, or is this the best way?
First, use semicolons behind commands to suppress output, it really makes a difference in performance:
Then, dot-operators (
.*,./, etc.) are for element-wise operations. The multiplication you do inside the arrayfun (dx .* sum(exp(...))) is a scalar times a vector. In this case element-wise and normal multiplications are the same. It is a good habit to keep normal multiplications for scalar*vector; it helps prevent bugs.Then, the
arrayfunis unneccesary. You can accomplish the same like so:The product
-2j*pi*dxis a product between all scalars. The product(-M:dx:M).'*xhowever is a product between matrices. Sincesumsums down the columns (dimension 1) by default, the results are the same. This solution has larger memory overhead, but is a lot faster thanarrayfun.Note that I’ve used
.'for transpose. In Matlab, the notationA'means conjugate transpose, andA.'means normal transpose. Especially in the context of complex math like you have, this is very important. Learn the difference, and remember it well.