why is my program not working ?
2 次查看(过去 30 天)
显示 更早的评论
x=-10:0.01:10
if x<-1
y=2*x+1
end
if x>=-1
y=2^x+1
end
plot(x,y)
??? Undefined function or variable 'y'.
Error in ==> Untitled at 8 plot(x,y)
0 个评论
回答(2 个)
Adam
2017-1-25
编辑:Adam
2017-1-25
x is a vector so x <-1 is also going to be a vector of logicals. In your case neither of your if statements returns true so y is undefined. You need something vectorised like the following (or a for loop if you want to be deliberately inefficient!):
x=-10:0.01:10;
y = zeros( size( x ) );
y( x < -1 ) = 2 * x( x < -1 ) + 1;
y( x>= -1 ) = 2.^x( x >= -1 ) + 1;
In your code x<-1 would only return true if every element in the vector x satisfied that condition, which is obviously not the case.
0 个评论
Purushottama Rao
2017-1-25
I think you are looking for something like
x=-10:0.01:10;
y(x<-1)=2*x(x<-1)+1;
y(x>=1)=2.^x(x>=1)+1;
plot(x,y)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!