0

I am working with a code in MATLAB and i have to implement function y= 1-2x(t-1) but when i try to code i get error.

How to get rid of this error?

    clc
    clear all
    close all
    t=-3:.1:3;
    x=heaviside(t);
    y=1-2*x(t-1)
    plot(t,y)
1
  • 1
    @CrisLuengo x(t-1) should create a new vector which contains original vector x shifted by one unit as per theory Commented Apr 13, 2019 at 16:29

1 Answer 1

2

There is a difference between evaluating a function and indexing an array, though they both use the same syntax in MATLAB.

Since x is an array, not a function, x(t-1) attempts to index into the array x, at locations t-1. However, t contains non-integer values and non-positive values. Indices in MATLAB must be between 1 and the number of elements in the array.

To shift an array by 1 to the right, you can use indexing as follows:

x([1,1:end-1])

Here, we repeat element #1, and drop the last element. There are other ways of accomplishing the same.

But, because one time unit does not correspond to one array element, since t is incremented by 0.1 every array element, this corresponds to a shift of 0.1 time units, not of 1 time unit.

To shift by one time unit, you’d have to modify the indexing above to shift the array by 10 elements. In the general case, it is posible that 1 time unit does not correspond to an integer number of array elements, for example if the increment had been 0.3 instead of 0.1. In this case, you need to interpolate:

interp1(t,x,t-1,'linear','extrap')

Here we are reading outside of the input array, and therefore need to take care of extrapolation. Hence that last argument to the function call. You can also choose to fill extrapolated values with zeros, for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.