Search code examples
arraysmatlabsignal-processing

Matlab: Problem with logical indexing (combining two vectors with different sample rate)


I have in Matlab two time signals y1(t1) and y2(t2), see 1st diagram. The sample rate of t1 and t2 is different (t2 has a lower sample rate).

Goal: I want to mask y1 based on the value of y2: When y2 is zero then y1 should be zero.

Problem: Because of the different sample rates, I have trouble achieving this --> do you have an idea?

The 2nd diagram shows the desired output for y3 (= masked y1) (green).

t1 = 0:0.01:10;
y1 = sin(t1*10);
% plot(t1, y1)

t2 = 0:1:10;
y2 = t2.*[0 1 1 0 0 1 1 1 1 0 0];
% stairs(t2, y2)

plot(t1, y1)
hold on
stairs(t2, y2)
hold off

% I need a y3 with time t1.
% y3 is zero when y2 is zero.
% y3 = ???

Current output for y1(t1) [blue] and y2(t2) [orange]:

enter image description here

Desired output for y3(t1) [green]:

enter image description here


Final Code After Using the Proposed Solution by User Wolfie

t1 = 0:0.01:10;
y1 = sin( t1 * 10 );
plot( t1, y1 )

t2 = 0:1:10;
y2 = t2 .* [ 0 1 1 0 0 1 1 1 1 0 0 ];
stairs( t2, y2 )

y2_us = interp1( t2, y2, t1,'previous' );
t2_us = interp1( t2, t2, t1 );
stairs( t2, y2 )
hold on
stairs( t2_us, y2_us )
hold off

plot( t1, y1 )
hold on
stairs( t2, y2 )
hold off

y3 = y1 .* ( y2_us > 0 );
plot( t1, y1 )
hold on
stairs( t2, y2 )
plot( t1, y3, 'LineWidth', 4, 'Color', [0, 0.39, 0] )
hold off

enter image description here


Solution

  • You can upsample y2 to share a timebase with y1:

    % upsample y2 to share timebase t1. 'previous' interp used to mimic
    % 'stairs' behaviour, i.e. hold previous value
    y2_us = interp1(t2,y2,t1,'previous');
    

    Then create the new array y3 based on y1 and y2:

    % Create y3 with timebase t1: =y1 if y2>0, =0 otherwise
    y3 = y1 .* (y2_us>0);
    

    Plot to confirm:

    plot(t1, y1)
    hold on
    stairs(t2, y2)
    plot(t1, y3)
    hold off
    

    plot