How do I perform statements on the dependent variable of a graph in MATLAB?

Deadly 提交于 2019-12-12 06:35:46

问题


I would like to know how to grab a specific number from an interval to test it and later be able to built a different functions under one graph. For example (in this case the 'x' variable),

 x 0:.5:5;

 Ids=ones(x);
 figure;hold on;

 for n = 1:5
     if(x < 3.0) %problem here
         Ids(n) = plot(x,x.^x);
     else 
         if (x > 4.0)  %and here
            Ids(n) = plot(x,-x.^x);
         end
     end
 end

EDIT

What I really want to do in MATLAB is to be able to do the following piecewise function:

y(x) = {  0                   (t - 5) < 0
       { (t - 5)*(t - x)      x < (t - 5)
       { (t + x^2)            x >= (t - 5)

I don't seem to understand how to graph this function since x = 0:.5:10 and t = 0:.1:10. I know how to do this without the t, but I get lost when the t is included and has different intervals compared to the x.


回答1:


It's a little unclear from your code what you are trying to do, but it appears that you want to create and plot a function f(x) that has the following form:

f(x) = [ x     for 3 <= x <= 4
       [ x^x   for x < 3
       [ -x^x  for x > 4

If this is what you want to do, you can do the following using logical indexing:

x = 0:0.5:5;  %# 11 points spaced from 0 to 5 in steps of 0.5
y = x;        %# Initialize y
index = x < 3;                   %# Get a logical index of points less than 3
y(index) = x(index).^x(index);   %# Change the indexed points
index = x > 4;                   %# Get a logical index of points greater then 4
y(index) = -x(index).^x(index);  %# Change the indexed points
plot(x,y);                       %# Plot y versus x



回答2:


You may be looking for piecewise polynomials: http://www.mathworks.com/help/techdoc/ref/mkpp.html

Otherwise, I would suggest making two vectors, "x" and "y", so to speak, and filling y by iterating through x and applying your conditions and results, then plot y against x. This will avoid the need to hold the plot.

If you want to animate the drawing, add plot() to the for loop followed by "drawnow". It's been a while since I had to animate plots though so I would suggest tutorials for drawnow and animation.



来源:https://stackoverflow.com/questions/4357995/how-do-i-perform-statements-on-the-dependent-variable-of-a-graph-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!