How to rewrite my code so it's faster?

3 views (last 30 days)
Shayma Al Ali
Shayma Al Ali on 10 Aug 2022
Commented: dpb on 10 Aug 2022
I need to filter out some data from a variable called track1.ph. This variable contains photon height data. Another variable called track1.surf_type contains surface mask data for the photons in track1.ph. However, track1.surf_type is organized by segments and there's no variable to determine which segment each photon in track1.ph belongs to. Another variable track1.seg_ph contains information on the photon count for each segment so I can use track1.seg_ph to deduce which segment a photon belongs to. My code is meant to identify which segment a photon belongs in and identify if that photon is classified as an ocean surface photon. My code:
ph=[]; ph_id=[];
for i=1:length(track1.seg_ph)
if i==1
l= 1:track1.seg_ph(i);
if l ~= 0
k=track1.ph(1:track1.seg_ph(i));
if track1.surf_type(2,i) == 1
ph=[ph; k];
ph_id=[ph_id; l'];
end
end
else
f=ph_id(end);
ffl=ph_id(end)+track1.seg_ph(i);
l=f:ffl;
if ffl ~= 0
k=track1.ph(l);
if track1.surf_type(2,i) == 1
ph_id=[ph_id; unique(l)'];
ph_id=unique(ph_id);
ph=[ph; track1.ph(ph_id)];
end
end
end
end
However, its taking a long time to run this code. Is there any way I can write my code so its more efficient?
  1 Comment
dpb
dpb on 10 Aug 2022
ph=[ph; track1.ph(ph_id)];
This is probably the biggest culprit -- dynamic reallocation -- if you know the final result size preallocate to that size and index into it; if you don't/can't calculate the final size a priori, then set it to a large-enough(*) size to an array of NaN and index into it. When done save with
ph=ph(isfinite(ph));
to reduce to final size.
(*) Or a fairly large size like 1000, say, and then allocate another chunk as needed.
Beyond that, think we'd need to see an example of the data sets and an example of the actual desired output to be able to see what's really going on without a lot of effort to try to dig through the (uncommented) code.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by