图形matlab上的标记点

时间:2014-12-08 20:44:27

标签: matlab point

我有这个函数绘制特定的等式:

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的函数并将函数标记为root。假设我知道要标记的根的x,y。

我该怎么做?一旦我打电话给draw,图表就会在没有根据的情况下绘制。

1 个答案:

答案 0 :(得分:1)

根据您的评论,您可以在现有功能中添加几行以达到您想要的效果。请注意,如果您事先知道根的位置,则更容易,您可以在代码中跳过该部分。它评论过,所以应该很容易理解。请告诉我,如果我离开赛道或有什么不清楚的地方:

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')

其中输出的内容如下:

enter image description here

这是你的想法吗?