数组未定义

时间:2016-01-12 21:56:42

标签: arrays matlab

我仍然感到困惑,为什么我不能知道我的数组这个小算法的结果。该阵列有近1000个数字1-D。我试图找到每个峰值的峰值和指数。我确实找到了峰值,但我找不到它们的指数。你能帮帮我吗?无论索引如何,我都想绘制所有值。

%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');

2 个答案:

答案 0 :(得分:4)

这是你的错误:

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

tt是一个包含数字0tmax-1的数组。将t1_n定义为t1_n = 1:5:tt不会创建数组,而是创建一个空矩阵。为什么?表达式t1_n = 1:5:tt将仅使用数组tt的第一个值,因此减少为t1_n = 1:5:tt = 1:5:0 = <empty matrix>。当然,当您稍后尝试访问t1_n时,就好像它是一个数组(peak_time(k) = t1_n(i))一样,您将收到错误。

您可能希望与{/ 1>交换t1_n = 1:5:tt

t1_n = 1:5:tmax;

答案 1 :(得分:0)

您需要正确索引tt数组。 你可以用

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)

你也可以减少一些代码,有些变量似乎没有使用,或者可能没有必要 - 包括t1_n变量:

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);