如何在MATLAB中繪製給定半徑的圓?
MATLAB 是一款可以執行各種與數學、工程和技術相關的操作和任務的工具。例如,我們可以使用 MATLAB 繪製各種形狀,例如圓形、正方形、矩形、三角形等。為此,我們只需要在 MATLAB 程式設計中編寫一段程式碼並輸入所需的引數,例如圓的半徑、矩形的寬度和高度等。
本教程將解釋如何使用 MATLAB 繪製指定半徑的圓。眾所周知,在數學和幾何中,圓是由連線到稱為圓心的固定點的幾個等距點形成的基本封閉形狀。
任意點與圓心之間的距離稱為圓的半徑。需要注意的是,圓是一個二維形狀,其所有點都位於同一平面上。
讓我們瞭解一下在 MATLAB 中繪製圓所涉及的步驟。
如何使用 MATLAB 繪製圓?
在 MATLAB 中繪製指定半徑的圓的分步過程如下所示。
步驟 (1) - 開啟 MATLAB 命令視窗。
步驟 (2) - 建立一個變數來儲存圓的半徑。
步驟 (3) - 使用函式繪製圓。這可以透過以下兩種方式完成
使用矩形函式。
透過建立行向量。
步驟 (4) - 將軸限制設定為相等,以便正確顯示圓。
因此,繪製指定半徑的圓是一個簡單的四步過程。
現在,讓我們在 MATLAB 中舉一些繪製圓的例子。
(1). 使用 MATLAB 中帶有“曲率”屬性的“rectangle”函式繪製圓
在 MATLAB 中,有一個內建函式“rectangle”,它具有“曲率”屬性。使用此函式和屬性,我們可以繪製具有指定半徑的圓。
示例 (1)
下面的 MATLAB 程式演示瞭如何使用“rectangle”函式繪製半徑為 r 的圓。
% MATLAB code to draw a circle of radius R % Specify the radius of the circle R = 10; % Create a figure to plot the circle figure; % Draw the circle using the rectangle function rectangle('Position', [-R, -R, 2 * R, 2 * R], 'Curvature', [1, 1]); % Set axis limit to equal to display the circle correctly axis equal; % Add a title to figure title('Circle with Radius R');
輸出

程式碼解釋
在這個 MATLAB 程式碼中,我們首先定義圓的半徑“R”。然後,我們建立一個圖形來繪製和顯示圓。之後,我們使用“rectangle”函式,並將“Curvature”屬性設定為 [1, 1] 來繪製半徑為“R”的圓。為了確保圓正確顯示,我們將軸限制設定為相等。
當我們執行此程式碼時,半徑為 R = 10 的圓將被繪製並顯示在一個圖形中。
(2). 透過在 MATLAB 中建立行向量來繪製圓
這是在 MATLAB 中繪製圓的另一種方法。下面的示例程式演示瞭如何透過建立兩個固定點之間均勻分佈的點的行向量來繪製具有指定半徑的圓。
示例 (2)
% MATLAB program to draw a circle % Define the radius of the circle R = 7; % Create a row vector v = linspace(0,2*pi,200); % Generate x-coordinates x = R * cos(v); % Generate y-coordinate y = R * sin(v); % plot the circle. plot(x, y); % Set axis limit to equal to display circle correctly axis equal; % Add a title to the plot title('Circle with Radius R');
輸出

程式碼解釋
在此 MATLAB 程式碼中,我們首先定義圓的半徑“R”。然後,我們使用“linspace”函式建立一個行向量,該函式建立兩個點之間 200 個均勻分佈的點。
之後,我們使用此向量生成 x 軸和 y 軸座標來繪製圓。然後,我們使用這些 x 和 y 座標使用“plot”函式繪製圓。
最後,我們將軸限制設定為相等以正確顯示圓。
這就是我們如何使用行向量繪製具有指定半徑的圓。
(3). 繪製使用者提供的半徑為 R 的圓
在 MATLAB 中,我們還可以允許使用者輸入圓的半徑。
下面的 MATLAB 程式演示瞭如何透過將半徑作為使用者輸入來建立圓。
示例 (3)
% MATLAB code to draw a circle of radius R % Take input for the radius of the circle R = input('Enter the Radius of the Circle = '); % Create a figure to plot the circle figure; % Draw the circle using the rectangle function rectangle('Position', [-R, -R, 2 * R, 2 * R], 'Curvature', [1, 1]); % Set axis limit to equal to display the circle correctly axis equal; % Add a title to figure title('Circle with Radius R');
輸出
輸入圓的半徑 = 15

程式碼解釋
此 MATLAB 程式碼的實現與之前的程式碼相同。唯一的區別是,在這裡我們允許使用者使用“input”函式輸入圓的半徑值。
結論
總之,MATLAB 提供了多種方法來繪製或繪製具有指定半徑的圓。在本教程中,我解釋了在 MATLAB 中繪製圓的兩種最常見和最簡單的方法。您可以嘗試使用不同的半徑值來繪製圓。