How to plot function

I'm working on a question where I am executing a function y = staircase(x) where
y = [ 0 if x <= 1 , 1 for 1<x<=2 & 2 if 2<x ]
So far I have;
function y = staircase(x)
for x = -3:0.01:3
if x <= 1
y = 0;
elseif x > 1 && x <= 2
y = 1;
else x > 2;
y = 2;
end
end
My question is how do I plot such a function?

回答 (3 件)

Ben11
Ben11 2014 年 7 月 29 日

0 投票

A lazy way would be like this:
figure
hold on
plot((-3:0.01:1),0,(1.01:0.01:2),1,(2.01:0.01:3),2,'LineWidth',2)
line('XData',[1 1],'YData',[0 1],'LineStyle',':');
line('XData',[2 2],'YData',[1 2],'LineStyle',':');
hold off
which gives this:
Do you need to write the plotting part in your function or you simply want to look at the staircase for some other purpose?
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 7 月 29 日
編集済み: Azzi Abdelmalek 2014 年 7 月 29 日

0 投票

x is an input argument, you can't assign values to x inside the function.
save this function as staircase.m
function y = staircase(x)
for k=1:numel(x)
if x (k)<= 1
y(k) = 0;
elseif x(k) > 1 && x(k) <= 2
y(k) = 1;
else x(k) > 2
y(k)= 2;
end
end
Then in Matlab Windows Command or in a new script write
x=-3:0.1:3 ; %assign values to x
y = staircase(x);
plot(x,y)

4 件のコメント

Hardik
Hardik 2014 年 7 月 29 日
Why do you write in "for k = 1:numel(x)"? Could you explain that.
Ben11
Ben11 2014 年 7 月 30 日
Because you want to evaluate your staircase function for every x you've got, so numel(x) allows to loop through all the values of the array in which X is stored
Hardik
Hardik 2014 年 7 月 30 日
When I run the script with the addition of the numel, matlab gives me an error saying Not enough input arguments.
Ben11
Ben11 2014 年 7 月 30 日
As Azzi suggested, you have to define x before you call staircase. I ran his code and it works well. Do the following:
1) Define x in the command window
x = -3:0.1:3;
2) Once this is done, you can then call staircase(x) and plot the result:
y = staircase(x);
plot(x,y)

サインインしてコメントする。

Star Strider
Star Strider 2014 年 7 月 29 日

0 投票

I built my own staircase function, because I didn’t want to create a separate function file.
This is how I plotted it:
x = -3:0.01:3;
staircase = @(x) [(0*(x <= 1)) + (1*((x > 1) & (x <= 2))) + (2*(x > 2))];
sc = staircase(x);
figure(1)
plot(x, sc)
axis([xlim -0.5 2.5])
The axis call makes it visible over its range.

カテゴリ

質問済み:

2014 年 7 月 29 日

コメント済み:

2014 年 7 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by