How to pre-allocate my loop for speed?

조회 수: 1 (최근 30일)
Daryna Butash
Daryna Butash 2021년 7월 26일
댓글: Star Strider 2021년 7월 29일
Hi,
I have a script to help process my collected altimeter data to derive seagrass heights. My script isnt quite working as one of my loops doesn't want to run properly and has an error of exceeding matrix bounds.
This is the loop that doesn't work: It is finding peaks above the seabed which it assumes are seagrass and the lower peaks as the seabed. I hope this makes sense.
for i = 1:length(ping_time)
[pks,locs] = findpeaks(bin_corr(:,i),'NPeaks',3,'MinPeakDistance',3,'MinPeakProminence',4); % tuning units are distance = bin number, prom = correlation value
if length(locs) == 1
pk_seagrass(i) = NaN;
pk_seabed(i) = bin_depth(locs);
elseif length(locs) == 2
pk_seagrass(i) = bin_depth(locs(1));
pk_seabed(i) = bin_depth(locs(2));
elseif length(locs) == 3
pk_seagrass(i) = bin_depth(locs(1));
pk_seabed(i) = bin_depth(locs(3));
elseif length(locs) == 0
pk_seagrass(i) = NaN;
pk_seabed(i) = NaN;
end
end
Any help or suggestions are much appreciated! Thank you :)
  댓글 수: 1
Jan
Jan 2021년 7월 26일
Please post a copy of the complete error message. It contains important information and sharing thos makes it easier to help you.

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2021년 7월 26일
I am not certain what the problem is, however the preallocation would be straightforward:
pk_seagrass = NaN(1,length(ping_time));
pk_seabed = NaN(1,length(ping_time));
This produces row vectors for both variables. Put them just above the for call.
.
  댓글 수: 2
Daryna Butash
Daryna Butash 2021년 7월 29일
Hi! Thank you very much for answering! I actually found the problem and it was nothing to do with the code and it actually worked very well, I realised that it was me using different editions of matlab (2020a and a 2021a one) with the latest one having no problems. Very glad to have it working, thank you for your time!
Star Strider
Star Strider 2021년 7월 29일
As always, my pleasure!
Note that preallocating is always appropriate. In my experience, it results in about a 20% improvement in execution speed. This is not always obvious with small arrays, however can reduce the processing time for large arrays by several minutes, even in computers with SSDs.
.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by