why is my program not working ?

2 次查看(过去 30 天)
Iulian Popa
Iulian Popa 2017-1-25
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)

回答(2 个)

Adam
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.

Purushottama Rao
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)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by