Search code examples
matlabdata-analysissampling

Data analysis in Matlab


I have a time vector in Matlab which does not have consistent sampling time, ex. t = [0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.9 3 3.1], I have another vector which is time based as a = [2 5 2 4 5 7 8 0 10 1 0 25 6 14 5 2 7 98], when I plot(t,a) there is straight line connecting the two points with larger sampling time, how can I remove these gaps where the sampling time is not consistent and it jumps to larger value? I know defining NaN between 0.7 and 1.3 and also 2 and 2.9 in t and also in a for the same interval might help, but how to distinguish if sampling time changes?


Solution

  • Maybe you can try the following codes, and here are two approaches that you can make it:

    • Approach 1: adding nan
    clc;
    clear;
    close all;
    
    t = [0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.9 3 3.1]
    a = [2 5 2 4 5 7 8 0 10 1 0 25 6 14 5 2 7 98]
    
    dt = diff(t);
    idx = find(dt > mode(dt));
    tC = mat2cell(t',[idx(1),diff([idx,length(t)])]);
    aC = mat2cell(a',[idx(1),diff([idx,length(t)])]);
    nadd = dt(idx)/mode(dt);
    T = [];
    A = [];
    for i = 1:length(nadd)
      T = [T; tC{i};ones(int32(nadd(i)),1)*nan];
      A = [A; aC{i};ones(int32(nadd(i)),1)*nan];
    endfor
    T = [T;tC{end}];
    A = [A;aC{end}];
    
    plot(T,A)
    

    enter image description here

    • Approach 2: dividing vector by intervals
    clc;
    clear;
    
    t = [0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.9 3 3.1]
    a = [2 5 2 4 5 7 8 0 10 1 0 25 6 14 5 2 7 98]
    
    dt = diff(t);
    idx = find(dt > mode(dt));
    tC = mat2cell(t',[idx(1),diff([idx,length(t)])]);
    aC = mat2cell(a',[idx(1),diff([idx,length(t)])]);
    
    hold on;
    arrayfun(@(k) plot(tC{k},aC{k}),1:(length(idx)+1));
    

    enter image description here