# Graphing a Piecewise Function with Loops and Vectors

45 ビュー (過去 30 日間)
Rebecca Lockburner 2020 年 4 月 30 日

Hello all, this is a homework question I have been stuck on. (I am in CS101 so I am brand new at this)
The problem in question is as follows: So far our professor has not specifically mentioned the piecewise function in matlab so I believe I am unable to use that.
The only code I was able to come up with is the loops code which provided a graph that looked correct. However, with the code where I am supposed to use "vectored code" I am a little confused on the wording. The code I have come up with is below but I keep receiving an error. Please help!
%loops code
cnt = 0;
t=(-6*pi:pi/10:6*pi);
y=0;
for i = t
cnt = cnt + 1
if i <= 0
y(cnt) = 0;
elseif i > 0
y(cnt) = sin(i);
end
end
plot(t,y, '-b');
grid on;
xlabel('\bft');
ylabel('\bff(t)');
xlim([-6*pi 6*pi]);
%vectored code
t = linspace(-6*pi, 6*pi, pi/10);
s = sin(t);
y = 0;
if s>0
y = sin(t);
else
y = 0;
end
plot(t, y, '-b');
grid on;
xlabel('\bft');
ylabel('\bff(t)');
xlim([-6*pi 6*pi]);

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

### 回答 (1 件)

rajat aggarwal 2020 年 5 月 13 日

In vectored code there are lot of mistakes which can be improved.
1) Using of linspace function. You mentioned pi/10 as third argument but third argument in linspace function is number of points you need. You can simply use above statement instead of using linspace.
2) In for loop code, you are taking sine of those numbers which are positive in vector 't' which is different from question asked . If you want to generate the graph similar to above for loop code. You should compare elements of t with zero. You took sin(t) first and then companring it with zero which will produce wrong result.
Some intelligent tricks for vectorising your code are give below.
t>0 will return index of arrays where elements of t are smaller than zero.
t(t<0) = 0 will make them zero.
t(t>0) =sin(t(t>0)) will take the sin of positive numbers.
see the below vector code of 'for loop'.This is not the actual answer:
t=(-6*pi:pi/10:6*pi);
x=t;
t(t<0) = 0;
t(t>0) = sin((t(t>0)))
plot(x, t, '-b');
grid on;
xlabel('\bft');
ylabel('\bff(t)');
xlim([-6*pi 6*pi]);
3) If you want to solve the homework question here is the code.
t=(-6*pi:pi/10:6*pi);
y = sin(t);
y(y<0) = 0;
plot(t,y, '-b');
grid on;
xlabel('\bft');
ylabel('\bff(t)');
xlim([-6*pi 6*pi]);

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

### カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

### Community Treasure Hunt

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

Start Hunting!