I want to plot a function y=1-exp(c) ,where as the range of x is defined. The plot is to be between x and the function y. The plot just shows just 1 point instead of showing a series of points exponentially.I am new in Matlab.Sp,please help me where I am going wrong Here is the code:
我想画出一个函数y=1-exp(c)在x的取值范围内。这个图是在x和y之间,这个图只显示了1个点而不是指数级数。我是新手。Sp,请帮助我在哪里出错这是代码:
for x = -10:0.25:10
if(x>0)
c=-6*x;
m=exp(c);
y = 1-m
end
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
end
2 个解决方案
#1
2
This should do it:
这应该这样做:
x = -10:0.25:10; % define the x vector
c= -5*x.*(x>0); % using a logical condition the 'if' is avoided
y = 1-exp(c); % calc y given c
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
no 'for' loop or 'if' needed...
没有“for”循环或“如果”需要……
#2
2
Your problem is the for loop. It is resetting the value of y and re-ploting that one point each loop. You don't need that loop at all. This code will do the trick for y = 1-exp(A*x)
你的问题是for循环。它重新设置y的值并重新绘制每个循环的一个点。你根本不需要那个循环。这段代码将对y = 1-exp(A*x)进行操作
Edit (2012-10-30) OP says y is zero for x<=0. @Nate's code in the answer above is probably best, but here I use logical indexing to show a different way to do the same thing.
编辑(2012-10-30)OP说,y =0, x<=0。在上面的答案中,@Nate的代码可能是最好的,但是在这里,我使用逻辑索引来显示一种不同的方法来做同样的事情。
x = -10:0.25:10; % <vector>
y = zeros(size(x)); % prealocate y with zeros and make it the same size as x
y(x>0) = 1 - exp(-5*x(x>0)); % only calculate y values for x>0
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
#1
2
This should do it:
这应该这样做:
x = -10:0.25:10; % define the x vector
c= -5*x.*(x>0); % using a logical condition the 'if' is avoided
y = 1-exp(c); % calc y given c
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
no 'for' loop or 'if' needed...
没有“for”循环或“如果”需要……
#2
2
Your problem is the for loop. It is resetting the value of y and re-ploting that one point each loop. You don't need that loop at all. This code will do the trick for y = 1-exp(A*x)
你的问题是for循环。它重新设置y的值并重新绘制每个循环的一个点。你根本不需要那个循环。这段代码将对y = 1-exp(A*x)进行操作
Edit (2012-10-30) OP says y is zero for x<=0. @Nate's code in the answer above is probably best, but here I use logical indexing to show a different way to do the same thing.
编辑(2012-10-30)OP说,y =0, x<=0。在上面的答案中,@Nate的代码可能是最好的,但是在这里,我使用逻辑索引来显示一种不同的方法来做同样的事情。
x = -10:0.25:10; % <vector>
y = zeros(size(x)); % prealocate y with zeros and make it the same size as x
y(x>0) = 1 - exp(-5*x(x>0)); % only calculate y values for x>0
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')