Simplifying code for plot.
1 view (last 30 days)
Show older comments
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])
0 Comments
Accepted Answer
Star Strider
on 23 Oct 2016
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.
0 Comments
More Answers (1)
dpb
on 23 Oct 2016
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. >>
0 Comments
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!