MATLAB中fill函数向量参数含义及正方形生成逻辑咨询
fill Function with Vector Inputs Hey there, I totally get why this feels confusing when you're prepping for your MATLAB final—vector inputs to fill can seem like a black box at first, but let's break down your example step by step to make it click.
First, let's clarify the core behavior of fill when you pass in vectors for x and y:
- Each element in the
xvector pairs up with the corresponding element in theyvector to define a vertex (corner point) of your shape. - MATLAB draws lines connecting these vertices in the exact order they appear in the vectors.
- Crucially,
fillautomatically closes the shape by drawing a line from the last vertex back to the first one, then fills the enclosed area with your specified color.
Now let's unpack your exact example: fill([1 -1 -1 1],[1 1 -1 -1], 'k')
Let's list out each vertex by matching the index positions of x and y:
- Vertex 1:
x=1,y=1→ coordinates(1, 1)(top-right corner of the square) - Vertex 2:
x=-1,y=1→ coordinates(-1, 1)(top-left corner) - Vertex 3:
x=-1,y=-1→ coordinates(-1, -1)(bottom-left corner) - Vertex 4:
x=1,y=-1→ coordinates(1, -1)(bottom-right corner)
Here's how the shape comes together:
- MATLAB draws a line from
(1,1)to(-1,1)—that's the top edge of the square. - Next, it draws from
(-1,1)to(-1,-1)—the left edge. - Then from
(-1,-1)to(1,-1)—the bottom edge. - Finally, it automatically connects
(1,-1)back to(1,1)to close the shape—adding the right edge.
Once the square is closed, 'k' tells MATLAB to fill the entire enclosed area with black.
A quick extra note: The order of the vertices matters a lot! If you mixed up the order of elements in x or y, you'd end up with a different (possibly weird) shape instead of a square.
内容的提问来源于stack exchange,提问作者user538039

