Using findpeaks collapses the size of my array, how do i stop this happening?

1 Ansicht (letzte 30 Tage)
Hi everyone,
I have this code for my spectrum:
[spectrum2,locations] = findpeaks(spectrum,5e5);
locations = locations * 5e5;
spectrum3 = rand(length(spectrum),1);
for i = 1:length(spectrum)
for j = 1:length(locations)
if i == locations(j)
spectrum3(i) = spectrum(i);
else
spectrum3(i) = 0;
end
end
end
The size of my spectrum array is 50 million, but after using findpeaks and plotting the array size is collapsed to around 3000. I would like the array elements to be 0 unless they correspond to the location of a peak, in which instance I would like the element to be the value it was originally. I've tried using these loops to do that but the array comes out as a flat line - how do I achieve what I'm trying to do? Is there a simpler way?
Thanks!
Tom
  1 Kommentar
Adam Danz
Adam Danz am 15 Apr. 2021
Bearbeitet: Adam Danz am 15 Apr. 2021
The goal of the function is entirely unclear.
There are several critical problems that need to be addressed.
  1. What is locations? It appears in the 2nd line and is never defined. This should throw an error unless locations is a global variable but a function should not rely on global variables.
  2. spectrum3 should probably be named spectrum2. Otherwise, spectrum2 is never defined and spectrum3 is never used.
Some less critical but noteworthy issues:
  1. findpeaks is the name of a matlab function. Rename this function to avoid confusion and shadow problems.
  2. Instead of preallocating with rand(), why not use nan(), ones(), or zeros()?
  3. Instead of using length(), use numel(). What if a user enters an array that isn't a vector?
  4. The j-loop can be vectorized by using indexing if not eliminated complete (see critical list above).

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Amrtanshu Raj
Amrtanshu Raj am 19 Apr. 2021
Hi,
Based on your requirement, this snippet should solve your problem.
[peaks,locations] = findpeaks(spectrum); %find the peaks and the corresponding locations
spectrum2 = zeros(length(spectrum),1); % create a array of zeros with same size as original spectrum
spectrum2(locations) = peaks; %replace the zeros at the location of peaks with peak values.
Hope this helps !!

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by