Graphing a Piecewise Function with Loops and Vectors
조회 수: 8 (최근 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:
![](https://cdn.discordapp.com/attachments/554522337848983573/705264726862594089/unknown.png)
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]);
댓글 수: 0
답변 (1개)
rajat aggarwal
2020년 5월 13일
편집: 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]);
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!