Sending values to a matrix from if-elseif-else loop?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposta accettata
Adam
il 6 Mar 2015
Modificato: Adam
il 6 Mar 2015
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 Commenti
Più risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!