Home > OS >  How can I compute the plotting of a triangle given it's vertices on matlab?
How can I compute the plotting of a triangle given it's vertices on matlab?

Time:10-03

Given the vertices of the triangle (x1, y1), (x2, y2) and (x3, y3), how can I plot a triangle in matlab with a function? So far this is my attempt

function dibujatriangulo(x1,y1,x2,y2,x3,y3)
x=x2:x1
plot(x, y2 (x2-x1)/(y2-y1)(x-x2)

and likewise with the x2 and x3 and, x3 and x1 but it doesn't plot correctly. Any help would be appreciated.

CodePudding user response:

As suggested by @BillBokeey, plotting a triangle is indeed a matter of understanding the plot function. In essence, plot(x, y) connect the subsequent points specified by the lists x and y with line segments. The code below illustrates this in more detail. I hope this helps.

% Call plot function
PlotTriangle(0,0,1,0,0,1)


% Function to plot triangle
function [] = PlotTriangle(x1,y1,x2,y2,x3,y3)

    xlist = [x1, x2, x3, x1];
    ylist = [y1, y2, y3, y1];
    plot(xlist, ylist)
    axis([-2, 2, -2, 2])

end

CodePudding user response:

you can also use command patch

example

x=[0 1 .5];y=[0 0 1];
patch(x,y,[1 0 0])

the 3rd field colours the patch with red, the 3 components being red green blue desired contents each within range [0 255].

With patch you can plot any polygon, not just triangles.

  • Related