0

Is there a good way to speed up this block of matlab code (n in particular, can be large) using matrix operations, or anything? Over 1/4 of my execution time is in this small block of code.

% Get the bin indexes that we will place the network in
bins = [];
for n=low_freq:0.5:high_freq;
    bins = [bins, (n-spec_start)/spec_bin_size+1];
end

Test code:

spec_start=2400
spec_bin_size=0.5
low_freq = 2437
high_freq=2438

bins = [];
for n=low_freq:0.5:high_freq;
    bins = [bins, (n-spec_start)/spec_bin_size+1];
end

bins  % 75 76 77

bins = [];
bins = (low_freq:0.5:high_freq - spec_start)./spec_bin_size + 1;

bins  % empty?

1 Answer 1

6

You can skip the loop:

bins = ((low_freq:0.5:high_freq) - spec_start)./spec_bin_size + 1;

In situations where you can't do vectorized calculations as above, you should at least preallocate the output array

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

4 Comments

@strictlyrude27: Sorry for making you waste your time.
hmmmm, I think something is slightly off. I think the result of this script should be 75,76,77 .. but I get an empty matrix from your code. Test code included in edit'ed question. Thanks so much for the help!
a-ha, just a little adjustment to parens: ((low_freq:0.5:high_freq) - spec_start)./spec_bin_size + 1
missing square brackets. how about this:([low_freq:0.5:high_freq] - spec_start)./spec_bin_size + 1

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.