Warm tip: This article is reproduced from stackoverflow.com, please click
matlab signal-processing

Incorrect plotting of ramp sequence in Matlab

发布于 2020-04-10 16:08:56

I am trying to plot a discrete ramp sequence using Matlab, within the interval [-10, 10].

This is my code:

function Ramp()
   rampseq(-10, 10);
end

function rampseq (n1, n2)
    n = (n1:1:n2);
    stem (n, pw(n));
end

function y = pw(n)
    if (n < 0)
        y = 0;
        return;
    else
        y = n;
        return;
    end
end

I define the behavior of the sequence in the pw(n) function (short form for 'piecewise'). Note that if n < 0, the output should be 0 or else if n >= 0, the output should be n itself. However, the plot turns out to be:

This isn't the ramp sequence as the Y-values are not 0 when n < 0, contrary to the behavior defined in the pw(n) function. Where am I going wrong? Is the if statement being skipped for some reason? The Command Window does not show any error.

Questioner
S.D.
Viewed
55
Harry 2020-02-02 02:46

You are passing the whole vector n into the pw() function. However, the pw() function then compares n to 0, which is a scalar.

You could adjust your pw() function to operate on vector inputs like this:

function y = pw(n)
    y = n;
    y(n < 0) = 0;
end