Search code examples
matlabmatlab-figure

Color some samples of MATLAB figure with different color


I have a discrete signal x of length N traced in MATLAB using the command

stem(abs(x)); axis([0 N+6 0 4]);

The resulted figure is shown below:

enter image description here

My question I need only some values corresponding for example to index [7 10 11 12 15 18 48 50 52 60] to be colored with different color , let's say with red. How can I do that into my figure ?


Solution

  • Using Multiple Plots by hold on and Matrix Indexing

    You could possibly and alternatively place a plot on top of plot by using hold on. This does require an adjustment where you need a vector in this case Sample and Indices which specify the sample number/data point index. You can also use matrix indexing to get the amplitude/data points corresponding to the key point, Indicies.

    Using Two Plots

    %Vector relating to the sample/data point number%
    Sample = linspace(1,70,70);
    
    %Random test data%
    X = randi([0,2],1,70);
    stem(Sample,X);
    
    hold on
    %Key indices to change colour%
    Key_Indices = [7 10 11 12 15 18 48 50 52 60];
    
    %Matrix indexing to get values/amplitudes corresponding to key indices%
    X_Prime = X(Key_Indices);
    
    stem(Key_Indices,X_Prime,'r');
    
    axis([0 70 0 3]);
    hold off
    

    Ran using MATLAB R2019b