필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Thomas Nell
Thomas Nell 2021년 4월 15일
답변: Amrtanshu Raj 2021년 4월 19일
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
Adam Danz
Adam Danz 2021년 4월 15일
편집: Adam Danz 2021년 4월 15일
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).

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

답변 (1개)

Amrtanshu Raj
Amrtanshu Raj 2021년 4월 19일
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 !!

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by