How to store some varialbes from a very large loop?

1 view (last 30 days)
Hello,
I am sorry if this is a dumb question, I am not a very experienced programmer. All help is greatly appreciated.
I am trying to find the local maxima of a complex system. I have an array pattern (theta, dB) with multiple peaks. I have used findpeaks in the past to do this, however my values are now complex numbers and findpeaks does not support this. I am currently using a simple code to find this, which is shown below, but the way I am storing my values returns a matrix the size of the loop, with the values I want from the if statement, and the rest of the values are zero.
for n = 1:size(ArrayPattern_dB)-1
if ArrayPattern_dB(n)> ArrayPattern_dB(n+1) && ArrayPattern_dB(n)>ArrayPattern_dB(n-1);
disp(ArrayPattern_dB(n))
disp(theta_deg(n))
A(n) = ArrayPattern_dB(n);
B(n) = theta_deg(n);
Peaks = [B A];
end
end
I would like to just return a matrix that contains the value and location of the peaks, but I cannot think of a way to do this.
Thank you, Jason
  1 Comment
Youssef  Khmou
Youssef Khmou on 21 Apr 2014
First proposition : use the absolute value of the pattern (abs(.)) then apply the algorithm for peak detection,

Sign in to comment.

Accepted Answer

Ken Atwell
Ken Atwell on 21 Apr 2014
If you initialize 'A' and 'B' as not-a-number (NAN) vectors, you could delete the NANs after the loop using logical indexing.
Before the loop:
A = nan(size(Array_Pattern));
B = nan(size(Array_Pattern));
After the loop
A = A(~isnan(A));
B = B(~isnan(B));
By the way, I believe your 'for' loop needs a little work, and you want to begin at '2' and not '1'. MATLAB indexes begin with one, and accessing the zero'th element of an array is an error. If you begin your loop at 1, 'ArrayPattern_dB(n-1)' will trigger an error.
  1 Comment
Jason
Jason on 21 Apr 2014
Thank you, it worked perfectly. I was curious about the for loop as well. The reason I didn't start the loop at 2 was because with an odd number of elements array, there are peaks at the beginning and end of the pattern. However, I can always extend the domain by a few points so I am not clipping any data.
Thank you again for your help.
Jason

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!