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.

답변 (1개)

Jan
Jan 2021년 5월 27일
편집: Jan 2021년 5월 27일

0 개 추천

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

Ali Ece
Ali Ece 2021년 5월 27일
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 2021년 5월 27일
편집: Torsten 2021년 5월 27일
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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2021년 5월 27일

댓글:

Jan
2021년 5월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by