Help me write the function please

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.

Risposte (1)

Jan
Jan il 27 Mag 2021
Modificato: Jan il 27 Mag 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 Commenti

First of all thanks for your help, I'm trying to understend I'm trying to understand all of these but I couldn't understand this part ' x = linspace(-5,30,200); ' why we use the '200' and what is the function of the linspace command here?
Torsten
Torsten il 27 Mag 2021
Modificato: Torsten il 27 Mag 2021
It's the same as
x = -5:35/(200-1):30
@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.

Accedi per commentare.

Categorie

Scopri di più su MATLAB in Centro assistenza e File Exchange

Richiesto:

il 27 Mag 2021

Commentato:

Jan
il 27 Mag 2021

Community Treasure Hunt

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

Start Hunting!

Translated by