1

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?

1 Answer 1

2

First, use semicolons behind commands to suppress output, it really makes a difference in performance:

M  = 50;
dx = 0.1;
r  = 20;
x  = -r/dx : r/dx;

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 arrayfun is unneccesary. You can accomplish the same like so:

y = dx * sum( exp(-2j*pi*dx * (-M:dx:M).'*x) );

The product -2j*pi*dx is a product between all scalars. The product (-M:dx:M).'*x however is a product between matrices. Since sum sums down the columns (dimension 1) by default, the results are the same. This solution has larger memory overhead, but is a lot faster than arrayfun.

Note that I've used .' for transpose. In Matlab, the notation A' means conjugate transpose, and A.' means normal transpose. Especially in the context of complex math like you have, this is very important. Learn the difference, and remember it well.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 this is an awesome answer/advice, thank you! Just to clarify, when you say exp((-M:dx:M).' * x) -- is that supposed to be a matrix exponential, or is it doing something else? I've never used matrix exponentials for this!
@Mehrdad: No, expm() is the matrix exponential. exp( [some matrix] ) is just the element-wise exponential.
Ahhhh that makes more sense, I was wondering how to do that! Thank you! :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.