繁体   English   中英

Matlab图形上的标记点

[英]mark point on graph matlab

我有绘制特定方程的函数:

function [  ] = draw(  )

x=linspace(-2,2,400);
for i=1:400
y(i)=cos(x(i)^2)-5*x(i)*sin(x(i)/2);
end

plot(x,y)
title('2-D line plot for the equation')
xlabel('x')
ylabel('y')

end

现在,我想编写另一个函数,该函数将使用draw并将该函数的根标记出来。 假设我知道我要标记的根的x,y。

我怎样才能做到这一点? 一旦我叫draw ,就没有了我的根。

根据您的评论,您可以在现有函数中添加几行以实现所需的功能。 请注意,如果您事先知道根的位置,那么会更容易,并且可以跳过代码中的该部分。 已对此进行了评论,因此应该很容易遵循。 请告诉我我是否偏离轨道,或者有什么不清楚的地方:

clear
clc
close all

x=linspace(-2,2,400);

%// for i=1:400
%// y(i)=cos(x(i)^2)-5*x(i)*sin(x(i)/2);
%// end

%// Vectorized function
y= cos(x.^2)-5.*x.*sin(x./2);

%// If you already have the roots skip this part 

%// ================================================
%// Create function handles to find roots.
fun = @(x) cos(x^2)-5*x*sin(x/2);

x0_1 = -1; %// Initial guesses for finding roots
x0_2 = 1;
a1 = fzero(fun,x0_1);
a2 = fzero(fun,x0_2);

%// ================================================

%// At this point you have the x-values of both roots (a1 and a2) as well
%// as their y-values, corresponding to fun(a1) and fun(a2), respectively).

%// Plot the function
plot(x,y)

hold on

%// Use scatter to mark the actual points on the curve. Highly
%// customizable.
hS1 = scatter(a1,fun(a1),300,'+','MarkerEdgeColor',[0 .5 .5],'MarkerFaceColor',[0 .7 .7]);
hS2 = scatter(a2,fun(a2),300,'+','MarkerEdgeColor',[0 .5 .5],'MarkerFaceColor',[0 .7 .7]);

%// Generate text strings. There are other ways as well, like using
%num2string[...].
TextString1 = sprintf('Root 1 is at (%0.1f,%0.1f)', a1,fun(a1));
TextString2 = sprintf('Root 2 is at (%0.1f,%0.1f)', a2,fun(a2));


%// Place text with those 2 lines at the location you want.
text(a1-1,fun(a1)+1,TextString1)
text(a2+.25,fun(a2)+1,TextString2)

title('2-D line plot for the equation')
xlabel('x')
ylabel('y')

输出如下内容:

在此处输入图片说明

这就是您的想法吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM