Search code examples
matlabplotpiecewise

Plotting "saw-tooth like" functions on MATLAB


I'm trying to plot a piece-wise function (of the form y = αx + β) on a single plot, such that for different regions on the x-axis, I have different values of α and β for the function.

I want to make the locations (on the x-axis) of these steps modifiable at will instead of having a predetermined number of such piece-functions. When plotted, it should ideally look like set of lines of different slopes and intercepts, each separated by a spacing. So if my spacing vector has 10 elements, I wrote my code such that I will correspondingly have 10 different piece-functions for different regions on the x-axis.

Here is the code that I wrote.

x = linspace(0,100,10000);
y = zeros(1,10000);
spacing = 0:10:100;

alpha = linspace(1,3,length(spacing)); %setting arbitrary upper lim
beta = linspace(1,5,length(spacing));




for j = 1:length(spacing)
    for i=1:10000
        if x(i) <= spacing(j)
            y(i) = alpha(j)*x(i) + beta(j);
            i = i + 1;
        else
            j = j + 1;


        end  
    end



end

plot(x,y)

However, when I plot this, I get a single slope. It doesn't seem to be recognizing a change in spacing(j) due to the j = j + 1 iterator in the else statement

enter image description here

Any suggestions or help on how I should approach this would be much appreciated!


Solution

  • You should first iterate over x and then over spacing. Because for every element in x you are trying to find the correct interval. Then once you found that interval you should move to the next element of x and stop the iteration over spacing. You can do that using brake. If you don't do that then it will always choose the last interval, since x(i) <= spacing(end). See the code below:

    x = linspace(0,100,10000);
    y = zeros(1,10000);
    spacing = 0:10:100;
    
    alpha = linspace(1,3,length(spacing)); %setting arbitrary upper lim
    beta = linspace(1,5,length(spacing));
    
    for i=1:10000
        for j = 1:length(spacing)
            if x(i) <= spacing(j)
                y(i) = alpha(j)*x(i) + beta(j);
                break
            end  
        end    
    end
    
    plot(x,y)
    ylim([0 max(y)])
    

    The last line is to set y to start from 0.