Help me write the function please

13 Ansichten (letzte 30 Tage)
Ali Ece
Ali Ece am 27 Mai 2021
Kommentiert: Jan am 27 Mai 2021
I'm working on this question
function equation
y = 0;
list = (-5:30)
for x = list
if x => 9
y = 15*sqrt(4x)+10;
if -5<= x <= 30
y = 10*x + 10
end
if x<0
y = 10;
end
I wrote this function but I think its not true. Please help me.

Antworten (1)

Jan
Jan am 27 Mai 2021
Bearbeitet: Jan am 27 Mai 2021
The vectorized approach with logical indexing:
function equation
x = linspace(-5, 30, 200);
m = (x >= 9);
y(m) = 15 * sqrt(4 * x(m)) + 10;
m = (0 <= x & x < 9);
y(m) = 10 * x(m) + 10;
m = (x < 0);
y(m) = 10;
plot(x, y);
end
With a loop:
function equation
x = linspace(-5, 30, 200);
y = zeros(size(x));
for k = 1:numel(x)
if x(k) >= 9
y(k) = 15 * sqrt(4 * x(k)) + 10;
elseif 0 <= x(k) % No need to test x < 9 again!
y(k) = 10 * x(k) + 10;
else % No need to test x(k) again
y(k) = 10;
end
end
plot(x, y)
end
The compact version with logical masking:
function equation
x = linspace(-5, 30, 200);
% Logical mask: Value:
y = (x >= 9) .* (15 * sqrt(4 * x) + 10) + ...
(0 <= x & x < 9) .* (10 * x(idx) + 10) + ...
(x < 0) .* 10;
plot(x, y);
end
Although I assume, that this is a solution of a homework, I do think, that the 3 different approachs are useful to teach Matlab. Please try to understand the differences and do not simply copy&paste one of the codes.
  3 Kommentare
Torsten
Torsten am 27 Mai 2021
Bearbeitet: Torsten am 27 Mai 2021
It's the same as
x = -5:35/(200-1):30
Jan
Jan am 27 Mai 2021
@Ali Ece: As Torsten has written already, linspace produces a number of points between the limits. I've chosen 200 to get a nice diagram. With 10 you can see some corners in the plot. With 10000 the diagram is smooth also, but you create more points than your monitor can display. 200 is a fair guess.
Feel free to make some experiments. Use 8 points with x = linspace(-3, 5, 8) and display single points by:
plot(x, y, '.');
Do you see it? Experiments with code helps to learn Matlab.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by