Sending values to a matrix from if-elseif-else loop?

5 次查看(过去 30 天)
I took a class a few years back on MATLAB basics such as this, but I can't seem to recall how to do it now and I can't decipher it from the help page. My ultimate goal is to graph what is essentially a piecewise function, with "y" equaling different equations for certain ranges of "x" values. This is what I have so far:
theta = [0:0.01:6.28];
B_1 = 1.0583;
B_2 = 1.0989;
B_3 = 2.1461;
B_4 = 5.2356;
B_5 = 6.2823;
%%Create loop to define displacement diagram
if theta <= B_1,
y = 3x
elseif B_1 < theta <= B_2,
y = 4*sin(x)
elseif B_2 < theta <= B_3,
y = x^2
elseif B_3 < theta <= B_4,
y = 2*cos(pi/x)
else theta > B_4,
y = 3/2+cos(x)
end
plot(theta,y)
Those equations are essentially just placeholders for the actual equations I need to use, but that is effectively what I am trying to do. I have played with the syntax according to the help page, I have tried "elif" loops, and I can't seem to figure this out. I know there is a way to send my "y =" values to some type of matrix, but I am not sure if that is what I want to do since they only apply to certain regions of theta (my x values).
My question is how to display each "y = " on the same figure, when y has 5 different equations for 5 different regions of my independent variable, theta.
PS I am aware of a piecewise function in MATLAB, and I attempted that as well, but I feel like I was much further off there than I am here.

采纳的回答

Adam
Adam 2015-3-6
编辑:Adam 2015-3-6
y = zeros( size( x ) );
y( theta <= B_1 ) = 3 .* x;
y( theta > B_1 && theta <= B_2 ) = 4 .* sin( x )
...
plot( theta, y )
should give you a y vector with your piecewise definition in if you continue for the remainder of your conditions.
That solution uses logical indexing which is far better than resorting to loops and if statements in general.
It assumes that x is defined as a vector otherwise some of the syntax will likely not work if x is an n-dimensional array. Is x some array of values independent of theta or is x supposed to actually be theta?
  2 个评论
Tyler
Tyler 2015-3-6
编辑:Tyler 2015-3-6
Thank you, yes that seems like a much better way to solve for it in general.
x is supposed to actually be theta, so in that case would I replace x with theta for my actual equations? I was just using those dummy equations as placeholders until I solve for what the actual equations should be.
Adam
Adam 2015-3-6
Yes, just plug theta in and it makes a lot more sense.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by