Plot function with changing variable

2 次查看(过去 30 天)
So I have a function that approximately calculates the length of the space curve 2*sin(s),3*cos(s)*exp(s),s.^2/10.
function leng_straight = spacecurvelength(curve,a,b,n)
% Generating n x-points from a to b
syms s
xi= a:(b-a)/n:b;
yi=subs(curve,s,xi);% generating the y-values of the function
% assuming that between consecutive data points, the
% curve can be approximated by linear splines.
leng_straight=0;
m=length(xi);
% there are m-1 splines for m points
for i=1:1:m-1
dx=xi(i+1)-xi(i);
dy= yi(i+1)-yi(i);
leneach=sqrt(dx^2+dy^2);
leng_straight=leng_straight+leneach;
end
end
So I'm now trying to plot this function as I change the 'n' value which is the number of subintervals. Right now I'm getting a blank plot when I call it like this: I've tried changing the names of each of the 'length's to make it unique but no difference.
length = spacecurvelength(@(s) [2*sin(s),3*cos(s)*exp(s),s.^2/10],-4*pi,4*pi,2);
length = spacecurvelength(@(s) [2*sin(s),3*cos(s)*exp(s),s.^2/10],-4*pi,4*pi,5);
length = spacecurvelength(@(s) [2*sin(s),3*cos(s)*exp(s),s.^2/10],-4*pi,4*pi,10);
length = spacecurvelength(@(s) [2*sin(s),3*cos(s)*exp(s),s.^2/10],-4*pi,4*pi,20);
x=[2, 5, 10, 20];
y=length;
plot(x,y)
xlabel('n')
ylabel('length')
title(['Length of Space Curve as a function of n'])

采纳的回答

Walter Roberson
Walter Roberson 2015-5-24
curvelen = arrayfun(@(n) spacecurvelength(@(s) [2*sin(s), 3*cos(s)*exp(s), s.^2/10],-4*pi,4*pi,n), x);
plot(x, curvelen);
Note that using a variable named "length" is likely to cause trouble with using the MATLAB library function named "length".
  3 个评论
Walter Roberson
Walter Roberson 2015-5-24
No, arrayfun() causes the given anonymous function to be run once per array value (value in x in this case), returning back a vector of outputs. curvelen would be a vector the same length as x.
Are you allowed to use "for" ?
x = [2, 5, 10, 20];
numx = length(x); %this is the MATLAB function, not your variable
curvelen = zeros(1,numx);
for K = 1 : numx
curvelen(K) = spacecurvelength(@(s) [2*sin(s), 3*cos(s)*exp(s), s.^2/10],-4*pi,4*pi, x(K));
end
plot(x, curvelen)
Eric
Eric 2015-5-24
Yes that works. Thanks Walter. Appreciate it.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Smoothing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by