Cristian
Cristian

Reputation: 415

Octave/MATLAB plotting digital signals

Given data like this:

>> x = [0,3.0001,7,9];
>> y = [0 1 0 1];
>> plot(x, y);

I need the plot to look like a digital signal, not like a linear interpolation (see grey and blue lines).

Enter image description here

Why?? (You don´t really need to read this):

I'm plotting events given by sensors, so I have to plot the current state of the sensors vs time. The events are not refreshed with a given frequency. I just have the times when the state of the sensors change. My data sets are something like this:

Sensor 1 On time 0

Sensor 2 On time 0.05

Sensor 1 Off time 1.15

Sensor 2 Off time 1.55

...

I don´t know if MATLAB or Octave are appropriated to plot these kind of signals.

Upvotes: 2

Views: 1326

Answers (3)

Sreedevi
Sreedevi

Reputation: 98

Use stairs:

figure;
stairs(x,y);

Or

x = [0,3,7,9];
y = [0 1 0 1]; % Input

Add this code before plotting:

x1(1) = x(1);
j = 2;
for i=2:numel(x)
    x1(j) = x(i);
    j =j+1;
    x1(j) = x(i);
    j=j+1;
end
x1

j = 1;
for i=1:numel(y)-1
  y1(j) = y(i);
  j =j+1;
  y1(j) = y(i);
  j=j+1;
end
y1(j) = y(end);
y1

Result:

x1 = [0, 3, 3, 7, 7, 9, 9]
y1 = [0, 0, 1, 1, 0, 0, 1]

plot(x1, y1);

Upvotes: 4

mikkola
mikkola

Reputation: 3476

Essentially, your sampling frequency is too low to show the sharp level changes in the signal. You can mitigate the problem by defining a vector of x values with a greater sampling frequency, and modifying that appropriately for your sensor on/off times. Example:

Ns = 1000; % number of points to use
x = linspace(0, 12, Ns);
y = zeros(1,Ns); %// initialize to all zeros
y( x >= 3 & x <= 7 ) = 1; %// signal high when x in range [3,7]
y( x > 9 ) = 1; %// signal high when x greater than 9

figure;
plot(x, y);

Upvotes: 1

Zoltan Csati
Zoltan Csati

Reputation: 699

I don't know if there is such kind of plot in MATLAB. But you can tie that plot from segments.

x=[0,3.0001,7,9];
y=[0 1 0 1];
ax = axes;
for iSegment = 1:numel(x)-1
    jump = y(iSegment)+1 - y(iSegment);
    line([x(iSegment) x(iSegment+1)], [y(iSegment), y(iSegment)]);
    if jump < 0
        line([x(iSegment) x(iSegment)], [y(iSegment), y(iSegment+1)]);
    elseif jump > 0
        line([x(iSegment+1) x(iSegment+1)], [y(iSegment), y(iSegment+1)]);
    end
end

Upvotes: 1

Related Questions