Plot function with changing variable

조회 수: 3 (최근 30일)
Eric
Eric 2015년 5월 24일
댓글: Eric 2015년 5월 24일
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에서 Splines에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by