why is my program not working ?
2 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Adam
on 25 Jan 2017
Edited: Adam
on 25 Jan 2017
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 Comments
Purushottama Rao
on 25 Jan 2017
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 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!