Steven_art
Steven_art

Reputation: 153

Array not defined

I'm still confused why am not able to know the results of this small algorithm of my array. the array has almost 1000 number 1-D. am trying to find the peak and the index of each peak. I did found the peaks, but I can't find the index of them. Could you please help me out. I want to plot all my values regardless the indexes.

%clear all
%close all
%clc
%// not generally appreciated
  %-----------------------------------
   %message1.txt.
  %-----------------------------------
  % t=linspace(0,tmax,length(x)); %get all numbers
  % t1_n=0:0.05:tmax;
x=load('ww.txt');
tmax= length(x) ; 
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt;

x1_n_ref=0;
k=0;
for i=1:length(x4)
   if x4(i)>170
   if x1_n_ref-x4(i)<0
       x1_n_ref=x4(i);
       alpha=1;
   elseif alpha==1 && x1_n_ref-x4(i)>0
       k=k+1;
       peak(k)=x1_n_ref;  // This is my peak value. but I also want to know the index of it. which will represent the time.
        %peak_time(k) = t1_n(i); // this is my issue. 
        alpha=2;    
   end
 else
    x1_n_ref=0;
 end

end

   %----------------------
 figure(1)
 %  plot(t,x,'k','linewidth',2)
 hold on
 % subplot(2,1,1)  
 grid
  plot(  x4,'b'); % ,tt,x,'k'
 legend('down-sampling by 5');

Upvotes: 1

Views: 69

Answers (2)

user5623414
user5623414

Reputation:

You need to index the tt array correctly. you can use

t1_n = tt(1:5:end);  % note that this will give a zero based index, rather than a 1 based index, due to t1_n starting at 0. you can use t1_n = 1:tmax if you want 1 based (matlab style)

you can also cut down the code a little, there are some variables that dont seem to be used, or may not be necessary -- including the t1_n variable:

x=load('ww.txt');

tmax= length(x); 
x4 = x(1:5:end);
xmin = 170

% now change the code

maxnopeaks = round(tmax/2);
peaks(maxnopeaks)=0;        % preallocate the peaks for speed
index(maxnopeaks)=0;         % preallocate index for speed

i = 0;
for n = 2 : tmax-1
    if x(n) > xmin
        if x(n) >= x(n-1) & x(n) >= x(n+1)
            i = i+1;
            peaks(i) = t(n);
            index(i) = n;
        end
    end
end

% now trim the excess values (if any)
peaks = peaks(1:i);
index = index(1:i);

Upvotes: 0

dfrib
dfrib

Reputation: 73176

Here is you error:

tmax= length(x) ; 
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt;   % <---

tt is an array containing numbers 0 through tmax-1. Defining t1_n as t1_n = 1:5:tt will not create an array, but an empty matrix. Why? Expression t1_n = 1:5:tt will use only the first value of array tt, hence reduce to t1_n = 1:5:tt = 1:5:0 = <empty matrix>. Naturally, when you later on try to access t1_n as if it were an array (peak_time(k) = t1_n(i)), you'll get an error.

You probably want to exchange t1_n = 1:5:tt with

t1_n = 1:5:tmax;

Upvotes: 4

Related Questions