0

Is there a way to vectorize code of the same form as what I have below?

for k=1:length(channel_cuttoffs)
    [b a] = butter(5,channel_cuttoffs(k));
    pulse = filtfilt(b,a,pulse);
    eyediagram(downsample(pulse,10),3)
end

pulse is 10000x1 and channel_cuttoffs is 1x5.

mehmet
  • 1,631
  • 16
  • 21
romanbird
  • 178
  • 9
  • I don't think the `butter` function allows vectors as input, so I guess it is not really possible. You could go through `channel_cuttoffs` with `arrayfun` but I'm not sure this improves performance. – hbaderts Dec 23 '14 at 09:48
  • 2
    There's no reason to. These functions are all fairly heavyweight (especially the graphics output), so the time percentage spent on "loop overhead" is very small. Keep it readable. – Peter Dec 23 '14 at 13:38
  • I will keep it as is, in that case. – romanbird Dec 23 '14 at 17:37

1 Answers1

2

You could use arrayfun to vectorise the code.

Something like:

[b a] = arrayfun(@(x), butter(5, x), channelcuttoffs);
pulse = arrayfun(@(x, y), filtfilt(x, y, pulse), b, a);

I don't think you can do anything for eyediagram as it creates a figure not a numeric output.

However, it should be noted that arrayfun is slow see: arrayfun can be significantly slower than an explicit loop in matlab. Why? and http://www.mathworks.com/matlabcentral/newsreader/view_thread/253596 for more details. So you are probably better off just using a loop like you do in the question.

Community
  • 1
  • 1
nivag
  • 573
  • 2
  • 8
  • 1
    `arrayfun` does not vectorize; it's just a loop in disguise. In fact, it may be [slower](http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why) than a `for` loop. – Luis Mendo Dec 23 '14 at 16:22