How can I plot this Function in MATLAB?

조회 수: 1 (최근 30일)
jason
jason 2013년 3월 21일
I need help plotting a signal f(x) in matlab. The signal is defined as:
f(x) =
{ (x+1)/2 , if -1 <= x < 1
{ 1 , if 1 <= x < 2
{ 0 , else
I cant figure out how to plot f(x) or f(x+1) Any help would be greatly appreciated.
P.S The range of x is from -4:4

채택된 답변

Wouter
Wouter 2013년 3월 21일
편집: Wouter 2013년 3월 21일
I would make a function of it:
function y = custom_function(x)
% y = custom_function(x)
y = zeros(size(x)); %make y as big as x and fill it with zeros
first_situation = x >= -1 && x < 1;
second_situation = x >= 1 && x < 2;
y(first_situation) = (x(first_situation) + 1) / 2;
y(second_situation) = 1;
% the remainder of the values was already set to zero
end
to plot this function you would use:
x = -4:4; % set x from -4 to 4
y = custom_function(x);
plot(x,y)
or to plot x+1
x_2 = (-4:4)+1; % set x from -3 to 5
y_2 = custom_function(x_2);
plot(x_2,y_2)
  댓글 수: 2
jason
jason 2013년 3월 21일
Thanks for your reply. I liked your use of commenting. I had been trying for ages to get the plot to work in a "for" loop. Do you know if this is possible,or if i was in the wrong direction completely.
Wouter
Wouter 2013년 3월 26일
you can also do it in a for loop:
x = -4:4 % set x
y = zeros(size(x)); % make empty y
for i = 1:length(x) % loop through x, index i
if (x(i) >= -1) && (x(i) < 1)
y(i) = (x(i) + 1) / 2; % set y at position i
elseif (x(i) >= 1) && (x(i) < 2)
y(i) = 1; % set y at position i to 1
else
y(i) = 0; % not really required; y was already 0
end
end
plot(x,y,'r-') % plot x,y as red 'r' line '-'

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by