Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Matlab 互動式產生特定曲線:滑鼠取點畫直線與圓弧

在 Matlab 工程中,常常需要一批測試資料,例如帶有雜訊的特定曲線。以下做法是用滑鼠在座標系上取點,互動式產生由直線段與圓弧段組成的 x、y 座標序列,還能順手疊加高斯雜訊。

操作方式:先取一個起點,接著跳出選單選擇「直線」或「圓弧」。選直線再取一點;選圓弧則再取兩點,以三點擬合出圓弧並產生資料。重複若干段後輸出成檔。

主程式

clc, clear, close all
% figure
axis([0 1000 0 1000])      % 座標軸大小
axis square

x_out = []; y_out = [];    % 保存所有產生的資料
xy0 = ginput(1);           % 起點
temp_xy = xy0;             % 上一次取點
plot(xy0(1), xy0(2), '*')
axis([0 1000 0 1000]), hold on
axis square

n = 4;                     % 曲線段數
for i = 1:n
    res = menu('選擇', '直線', '圓弧');
    if (res == 1)
        xy1 = ginput(1);
        [x, y] = drawLine(temp_xy, xy1);
        x_out = [x_out x]; y_out = [y_out y];
        temp_xy = xy1(end, :);
        plot(x, y);
    else
        % 注意:圓弧 y 座標需唯一,扇形角度不可超過 180 度
        xy1 = ginput(2);
        [x, y] = getArc(temp_xy, xy1(1, :), xy1(2, :));
        x_out = [x_out x]; y_out = [y_out y];
        temp_xy = xy1(end, :);
    end
end

% 加上雜訊
noise = 2;                 % 雜訊幅度
for i = 1:length(x_out)
    y_out(i) = y_out(i) + random('Normal', -1 * noise, noise);
end

xy_file = [x_out' y_out'];           % 轉置為兩列
xy_file = sortrows(xy_file, 1);      % 依 x 座標排序,避免圓弧段順序顛倒
xy_file = [xy_file(:, 1)'; xy_file(:, 2)']   % 轉回兩列座標形式

figure
plot(xy_file(1, :), xy_file(2, :))

% 寫入 txt,檔名自動遞增
count = 1;
fileName = ['D:\data' num2str(count) '.txt'];
if (exist(fileName, 'file'))
    count = count + 1;
    fileName = ['D:\data' num2str(count) '.txt'];
end
fid = fopen(fileName, 'wt');
fprintf(fid, '%f,%f\n', xy_file);
fclose(fid);

兩點生成直線

function [x, y] = drawLine(A, B)
x = A(1):0.1:B(1);
y = (B(2) - A(2)) / (B(1) - A(1)) * (x - A(1)) + A(2);
end

三點生成圓弧

function [x, y] = getArc(A, B, C)
[c, r] = calcCircle(A, B, C);
a = c(1); b = c(2);

th = [A; B; C];
th2 = [th(:, 1) - a, th(:, 2) - b];
theta = atan2(th2(:, 2), th2(:, 1));
[theta_max, num_max] = max(theta);
[theta_min, num_min] = min(theta);

t = linspace(theta_min, theta_max, 1000);
x = r * cos(t) + a;
y = r * sin(t) + b;
plot(x, y, 'r-', th(:, 1), th(:, 2), 'o')
end

圓弧擬合(網路來源)

function [centre, radius] = calcCircle(pt1, pt2, pt3)
% calcCircle: Fit a circle to a set of 3 points
% 輸入三個二維點,回傳圓心與半徑;
% 若三點共線,圓心為 [0 0]、半徑為 -1。
% Author: Peter Bone   version 1.2 (mar 2008)

if nargin < 3
    error('Three input points are required.');
elseif ~isequal(numel(pt1), numel(pt2), numel(pt3), 2)
    error('The three input points should all have two elements.')
end

pt1 = double(pt1); pt2 = double(pt2); pt3 = double(pt3);
epsilon = 0.000000001;

delta_a = pt2 - pt1;
delta_b = pt3 - pt2;
ax_is_0 = abs(delta_a(1)) <= epsilon;
bx_is_0 = abs(delta_b(1)) <= epsilon;

% 兩線皆垂直 → 共線
if ax_is_0 && bx_is_0
    centre = [0 0]; radius = -1;
    warning([mfilename ':CollinearPoints'], ...
            'Points are on a straight line (collinear).');
    return
end

% 避免梯度為垂直,必要時交換點序
if ax_is_0
    tmp = pt2; pt2 = pt3; pt3 = tmp;
    delta_a = pt2 - pt1;
end
if bx_is_0
    tmp = pt1; pt1 = pt2; pt2 = tmp;
    delta_b = pt3 - pt2;
end

grad_a = delta_a(2) / delta_a(1);
grad_b = delta_b(2) / delta_b(1);

if abs(grad_a - grad_b) <= epsilon
    centre = [0 0]; radius = -1;
    warning([mfilename ':CollinearPoints'], ...
            'Points are on a straight line (collinear).');
    return
end

if abs(grad_a) <= epsilon
    tmp = grad_a; grad_a = grad_b; grad_b = tmp;
    tmp = pt1; pt1 = pt3; pt3 = tmp;
end

% 兩條中垂線的交點即圓心
centre(1) = ( grad_a * grad_b * (pt1(2) - pt3(2)) ...
            + grad_b * (pt1(1) + pt2(1)) ...
            - grad_a * (pt2(1) + pt3(1)) ) / (2 * (grad_b - grad_a));
centre(2) = ((pt1(1) + pt2(1)) / 2 - centre(1)) / grad_a ...
            + (pt1(2) + pt2(2)) / 2;

radius = norm(centre - pt1);

使用提醒

選單取點時會即時把每一段畫出來,全部完成後再把疊加雜訊的結果重新繪製,最後寫成「x,y」兩列的 txt 檔,方便直接匯入其他工程。要留意兩件事:圓弧目前假設 y 座標唯一,因此扇形角度不能超過 180 度;另外若相鄰兩點 x 座標相同,drawLine 會出現除以零,實務上可加一個判斷改成垂直線處理。

Copyright © Linux教程網 All Rights Reserved