필터 지우기
필터 지우기

Simplifying code for plot.

조회 수: 1 (최근 30일)
aquiano
aquiano 2016년 10월 23일
답변: dpb 2016년 10월 23일
How simplify my code to where I can write t=[0 .2 .5 1 2] instead of writing them individually as t1,t2 etc... And possibly plot it as just plot(x,y) to where I get the same graph. Below is the code I am referring to.
clear
t0=0
t1=.2
t2=.5
t3=1
t4=2
x=-6:12/100:6
y0=-2*sinh(x)./(cosh(x)-exp(-t0));
y1=-2*sinh(x)./(cosh(x)-exp(-t1));
y2=-2*sinh(x)./(cosh(x)-exp(-t2));
y3=-2*sinh(x)./(cosh(x)-exp(-t3));
y4=-2*sinh(x)./(cosh(x)-exp(-t4));
plot(x,y0,'--')
hold on
plot(x,y1)
plot(x,y2)
plot(x,y3)
plot(x,y4)
axis([-6 6 -4 4])

채택된 답변

Star Strider
Star Strider 2016년 10월 23일
This works:
tv = [0 .2 .5 1 2];
x = -6:12/100:6;
for k1 = 1:length(tv)
y(k1,:) = -2*sinh(x)./(cosh(x)-exp(-tv(k1)));
end
figure(1)
plot(x, y)
grid
axis([xlim -4 4])
legend('t = 0.0', 't = 0.2', 't = 0.5', 't = 1.0', 't = 2.0')
With a ‘t’ vector of only 5 elements, it’s easier to to just use a loop and some straightforward coding. With a longer vector, other approaches (using bsxfun and parsing the legend entries) would be more efficient.

추가 답변 (1개)

dpb
dpb 2016년 10월 23일
Simplest is probably to write the function as anonymous function then just loop over the t0 values building the array--
fy=@(x,t0) -2*sinh(x)./(cosh(x)-exp(-t0)); % anonymous function in x,t0
y=zeros(length(x),length(t)); % preallocate for output
for i=1:length(t),y(:,i)=fy(x.',t(i));end % evaluate function of t array
figure
hL=plot(x,y); % plot, save line handles
xlim([-6 6]),ylim([-4 4])
NB: when called the function made sure that x was column vector so output of fy would also be columnar. plot and friends presume that is the orientation of variables when y is an array. Fix up the line properties as desired using the line handles returned from plot. >>

카테고리

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