Produce the same result but without using a for-loop.

3 次查看(过去 30 天)
% Produce the same result but without using a for-loop.
% Increment
dx = 35/300;
% Independent variable
x = -5:dx:30; % x = linspace(-5,30,300)
for n = 1:length(x)
if x(n) >= 9
y(n) = 15*sqrt(4*x(n)) + 10;
elseif (x(n) >= 0) && (x(n) <= 9)
y(n) = 10*x(n) + 10;
else
y(n) = 10;
end
end
plot(x,y), xlabel('x'), ylabel('y'), grid on
  1 个评论
Rik
Rik 2021-4-6
This time I edited your question for you. Next time, please use the tools explained on this page to make your question more readable.

请先登录,再进行评论。

回答(2 个)

Cris LaPierre
Cris LaPierre 2021-4-6
编辑:Cris LaPierre 2021-4-6
This is a piecewise function. Perhaps the easiest way to do this is using the piecewise function.
If your assignment doesn't allow that, then create 3 vectors, one for each equation, and solve each for all values of x. Then multiply each by a logical array created from x and the corresponding conditional statement(s). Finally, add all three vectors together.
See Ch 12 of MATLAB Onramp if you need help creating the logical array, and Ch 6 if you need help on elementwise multiplication.
  8 个评论
Cris LaPierre
Cris LaPierre 2021-4-6
编辑:Cris LaPierre 2021-4-6
You have two competing conditions in your second case.
  • 0>=x means x less than or equal to 0.
  • x>=9 is the same as your condition for your first condition and means x greater than or equal to 9.
Can you see how the two conditions cannot be met? Think through how to define your ranges.

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2021-4-6
syms y(x)
y(x) = piecewise(x>=9, 15*sqrt(4*x)+10, 0>=x=<9, 10*x+10,10)
^^
MATLAB does not have an =< operator; it has a <= operator.
dx = 35/300;
xvalue = -5:dx:30;
fplot(y)
fplot() by default plots from -5 to +5 . Your assignment to xvalue does not affect that. To have it plot over a different interval, the interval would have to be passed as the second parameter, such as
fplot(y, [-5, 30])
Only the endpoints of the interval would be passed.
fplot() always chooses its own points to plot at. If you only want to plot at particular points, you should not use fplot(); you should use plot() instead.
plot() does not accept formulas, so you would need to
plot(xvalue, y(xvalue))

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by