gpt4 book ai didi

matlab - 如何使 MATLAB 绘图具有交互性?

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:57 28 4
gpt4 key购买 nike

我正在尝试创建一个简单的界面来绘制二次拉格朗日多项式。为此,您只需要 3 个点(每个点都有自己的 x、y、z 坐标),然后使用二次拉格朗日多项式对其进行插值。

制作静态版本很容易,甚至可以让用户在绘制曲线之前输入 3 个点。但用户也应该可以将绘图窗口中的现有点拖动到另一个位置,然后使用该点的新位置自动重新绘制曲线!

enter image description here

所以简而言之,用户应该能够将这些黑点拖到另一个位置。之后(或拖动时),曲线应该会更新。

function Interact()

% Interactive stuff here

figure();
hold on;
axis([0 7 0 5])

DrawLagrange([1,1; 3,4; 6,2])

function DrawLagrange(P)

plot(P(:,1), P(:,2), 'ko--', 'MarkerSize', 10, 'MarkerFaceColor', 'k')

t = 0:.1:2;
Lagrange = [.5*t.^2 - 1.5*t + 1; -t.^2 + 2*t; .5*t.^2 - .5*t];

CurveX = P(1,1)*Lagrange(1,:) + P(2,1)*Lagrange(2,:) + P(3,1)*Lagrange(3,:);
CurveY = P(1,2)*Lagrange(1,:) + P(2,2)*Lagrange(2,:) + P(3,2)*Lagrange(3,:);

plot(CurveX, CurveY);

我想我要么必须使用像 WindowButtonDownFcnWindowButtonUpFcnWindowButtonMotionFcn 这样的函数,要么使用 ImPoint图像处理工具箱。但是如何呢?

[编辑]它也应该适用于 3D,因为我想将这个概念推广到张量积表面。

最佳答案

好的,我从图像处理工具箱中搜索了有关 ImPoint 选项的更多信息,并编写了这个脚本。

由于 ImPoint 仅适用于 2D 设置(我想将其推广到 3D 以便能够处理曲面而不是曲线),这并不是一个可以接受的答案!但有人可能会从中受益,或者知道如何在 3D 中执行此操作。

% -------------------------------------------------
% This file needs the Image Processing Toolbox!
% -------------------------------------------------

function Interact(Pos)

% This part is executed when you run it for the first time.
% In that case, the number of input arguments (nargin) == 0.
if nargin == 0

close all;
clear all;
clc;

figure();
hold on;
axis([0 7 0 5])

% I do not know how to do this without global variables?
global P0 P1 P2

% GCA = Get handle for Current Axis
P0 = ImPoint(gca,1,1);
setString(P0,'P0');
P1 = ImPoint(gca,2,4);
setString(P1,'P1');
P2 = ImPoint(gca,6,2);
setString(P2,'P2');

% Call subfunction
DrawLagrange(P0,P1,P2)

% Add callback to each point
addNewPositionCallback(P0,@Interact);
addNewPositionCallback(P1,@Interact);
addNewPositionCallback(P2,@Interact);

else

% If there _is_ some input argument, it has to be the updated
% position of a moved point.
global H1 H2 P0 P1 P2

% Display X and Y coordinates of moved point
Pos

% Important: remove old plots! Otherwise the graph will get messy.
delete(H1)
delete(H2)
DrawLagrange(P0,P1,P2)

end

function DrawLagrange(P0,P1,P2)

P = zeros(3,2);
% Get X and Y coordinates for the 3 points.
P(1,:) = getPosition(P0);
P(2,:) = getPosition(P1);
P(3,:) = getPosition(P2);

global H1 H2
H1 = plot(P(:,1), P(:,2), 'ko--', 'MarkerSize', 12);

t = 0:.1:2;
Lagrange = [.5*t.^2 - 1.5*t + 1; -t.^2 + 2*t; .5*t.^2 - .5*t];

CurveX = P(1,1)*Lagrange(1,:) + P(2,1)*Lagrange(2,:) + P(3,1)*Lagrange(3,:);
CurveY = P(1,2)*Lagrange(1,:) + P(2,2)*Lagrange(2,:) + P(3,2)*Lagrange(3,:);

H2 = plot(CurveX, CurveY);

为了清楚起见,我添加了一些评论。

[编辑] 在预览中,语法高亮看起来不是很好!我应该定义要在某处突出显示的语言吗?

关于matlab - 如何使 MATLAB 绘图具有交互性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9646146/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com