使用fplot函数时如何矢量化? [英] How to vectorize when using fplot function?

查看:61
本文介绍了使用fplot函数时如何矢量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fplot.(我也可以使用plot,我只是找到了更多fplot的示例).我想绘制形式为y = m * x的两条直线其中m = V1和V2.V1和V2是标量.以下代码给我一个错误.

I am using fplot. (I could use plot as well I just found more examples of fplot). I want to plot two straight lines of the form y = m * x where m = V1 and V2. V1 and V2 are scalars. The following code gives me an error.

Matlab代码

fplot(@(x) V1,[-4 4],'green')
xlim([-4 4])
ylim([-4 4])

错误消息提示要向量化.我不确定该怎么做?稍后,我将使用meshgrid功能将指定的网格添加到该图中.

The error messages say to vectorize. I am not sure how to do this? I will be later adding to this graph a specified grid using meshgrid funtion.

[x,y]=meshgrid(-4:.5:4,-4:.5:4);

困扰我的是我没有在fplot语句中指定增量0.5.Matlab代码

What bothers me is that I am not specifying increment .5 in the fplot statement. The Matlab Code

fplot(@(x) V1,[-4 4],'green')

给出以下错误消息:

错误消息警告:函数在数组输入上的行为异常.至为了提高性能,请对函数进行适当的矢量化处理,以返回与输入参数相同的大小和形状的输出.

Error Messages Warning: Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your function to return output with the same size and shape as the input arguments.

  In matlab.graphics.function.FunctionLine>getFunction
  In matlab.graphics.function.FunctionLine/updateFunction
  In matlab.graphics.function.FunctionLine/set.Function_I
  In matlab.graphics.function.FunctionLine/set.Function
  In matlab.graphics.function.FunctionLine
  In fplot>singleFplot (line 234)
  In fplot>@(f)singleFplot(cax,{f},limits,extraOpts,args) (line 193)
  In fplot>vectorizeFplot (line 193)
  In fplot (line 163)
  In m01 (line 121) 

有人可以帮我把这些放在一起吗?谢谢.

Can someone help me put this together? Thank you.

推荐答案

您说您想用等式y = m * x绘制两条线,其中x是向量,m是标量V1和V2,因此您要在同一图形上为两个标量绘制2条线.

You said that you want to plot two lines with the equation y = m*x, where x is a vector and m is scalar V1 and V2 and hence you want to plot 2 lines for both the scalar on the same plot.

因此,您可以同时使用V1和V2将匿名函数直接放在fplot()命令中.

So you can directly put the anonymous function in fplot() command using both V1 and V2 one by one.

close all

% declare the x interval
x =[-4:1:4];


% declare the m values as V1 and V2
V1 = 3;
V2 = 4;

% plot the 1st function
fplot(@(x)V1*x, 'green')
% hold the axis to plot the
% 2nd function within the same axis
hold on
% plot the 2nd function
fplot(@(x)V2*x, 'red')

xlim([-4 4])
ylim([-4 4])
hold off

在声明函数时要注意的最重要的事情是声明函数是否必须使用点(.)运算符适用于正确地向量化该功能.

例如

y = @(x)x.^2 + 2*x;

这篇关于使用fplot函数时如何矢量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆