why is my program not working ?

1 visualizzazione (ultimi 30 giorni)
Iulian Popa
Iulian Popa il 25 Gen 2017
Risposto: Purushottama Rao il 25 Gen 2017
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)

Risposte (2)

Adam
Adam il 25 Gen 2017
Modificato: Adam il 25 Gen 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.

Purushottama Rao
Purushottama Rao il 25 Gen 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)

Categorie

Scopri di più su 2-D and 3-D Plots in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by