简体   繁体   English

在Matlab中绘制函数

[英]Plotting a function in Matlab

I'm interested in plotting the following function in Matlab, but without succes. 我对在Matlab中绘制以下函数感兴趣,但是没有成功。

在此处输入图片说明

I can't manage to plot the points. 我无法绘制点。

 x = -1:0.1:3;
 if (x<=1)
     y = x*x-x+1
     plot(x,y)
 else
     y = 2*x+3
     plot(x,y)
 end

The if statement you defines takes the condition for the entire array , which means all entries should adhere to the statement. 您定义的if语句采用整个数组的条件,这意味着所有条目都应遵守该语句。 Since only the first 21 adhere to the condition posed, the if statement goes to the else and plots a straight line. 由于只有前21个符合所构成的条件,因此if语句转到else并绘制一条直线。

Your equation for the first line is incorrect, since x*x results in an error since MATLAB assumes this to be a matrix multiplication and the sizes are not correct for that. 您的第一行方程式不正确,因为x*x导致错误,因为MATLAB认为这是矩阵乘法,并且大小不正确。 The reason you are not seeing this error is due to the if statement, since, as explained above, that never reaches this line. 您没有看到此错误的原因是由于if语句,因为如上所述,它永远不会到达此行。 You should change that equation using the dot-multiplication, which does things element-wise as opposed to array/matrix-wise. 您应该使用点乘法来更改该方程式,这是按元素方式而不是按数组/矩阵方式进行的。

The equation for the second line is correct. 第二行的方程式正确。

If your if/else statement would be correct your first plot would be overwritten by the second, since you did not specify the hold on switch to figures. 如果您的if/else陈述正确,那么您的第一个情节将被第二个情节覆盖,因为您未指定对数字的hold on

As a note I also used the semicolon ; 注意,我还使用了分号; after each statement, which prevents it from printing the output of a line to the console. 在每个语句之后,以防止其将行的输出打印到控制台。

x1 = [-1:0.01:1].';
x2 = [1:0.01:3].';
y1 = x1.^2-x1+1;
y2 = 2*x2+3;

figure;
hold on
plot(x1,y1)
plot(x2,y2)

情节

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

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