why is my program not working ?

조회 수: 1 (최근 30일)
Iulian Popa
Iulian Popa 2017년 1월 25일
답변: Purushottama Rao 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에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by