Help me write the function please
조회 수: 11 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
Jan
2021년 5월 27일
편집: Jan
2021년 5월 27일
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
Jan
2021년 5월 27일
@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.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!