Search code examples
matlabplotpiecewise

Matlab drawing points and show values


I have a simple plot question.

On x axis, the values are K, say from 2 to 12, discrete. On y axis, the values are C, say from 1 to 10, discrete.

My function is piecewise:

K if K<2C; K+2C if K>=2C;

I want to show the values at points (K,C):

(1,1) Show as 1 (1,2) Show as 1 (2,1) Show as 4 (2,2) Show as 2 ect.

How would I do that?

Many thanks,

Casper


Solution

  • You can use ndgrid to create K and C:

    [K C] = ndgrid(2:12,1:10);
    

    then use logical indexing to calculate the separate parts:

    z=zeros(11,10);
    ind = K>=(2*C);
    z(~ind) = K(~ind);
    z(ind) = K(ind)+2*C(ind);
    

    then plot any way you want:

    surf(C,K,z);
    

    or

    image(z);
    

    and others....