필터 지우기
필터 지우기

Anonymous Function

조회 수: 3 (최근 30일)
Jerry Walker
Jerry Walker 2011년 6월 24일
댓글: Steven Lord 2023년 1월 31일
[EDIT: 20110623 22:10 CDT - reformat - WDR]
I am having considerable difficulty with the program below. My goal is to be able to enter or change the Current Density (J) in the integral as an anonymous function. When j = 2*cos(theta)/r^3, the result should be about 31.4. Are there any other methods that would allow me to enter J inot the integral?
When I run I get the following error message:
??? Undefined function or method 'mtimes' for input arguments of type 'function_handle'.
When I swap the "%" on the operator inside the loops I get a 31.4, a good result.
clc
clear
close
r = 0.2;
dt = .1;
dp = .1;
jinput = input('Enter an expression for the Current Density (J)... > ','s')
jfactor = eval(['@(r,theta,phi)' jinput]);
% set initial total sum to zero
sum1 = 0;
% outer integral loop
for theta = 0:dt:pi/2
% inner integral loop
for phi = 0:dp:2*pi
% add the partial sums to the total sum
sum1 = sum1 + jfactor*r^2*sin(theta)*dt*dp;
%sum1 = sum1 + 2*cos(theta)/r^3*r^2*sin(theta)*dt*dp;
end
end
% display the output
fprintf('>The total current through the defined spherical shell is %g A.\n', sum1)
  댓글 수: 1
Steven Lord
Steven Lord 2023년 1월 31일
%{
jfactor = eval(['@(r,theta,phi)' jinput]);
%}
Don't use eval. Use str2func. [I've commented out the code above so the code below can run.] Since the input function isn't supported when running code in MATLAB Answers I've hard-coded the body of the function below.
jinput = 'r+theta.^phi';
jfactor = str2func(['@(r, theta, phi) ', jinput])
jfactor = function_handle with value:
@(r,theta,phi)r+theta.^phi
% check
jfactor(1, 2, 3) % 1+2^3 = 9
ans = 9

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2011년 6월 24일
jfactor becomes a function, and that function needs to be passed arguments.
sum1 = sum1 + jfactor(r,theta,phi)*r^2*sin(theta)*dt*dp;

추가 답변 (2개)

Jerry Walker
Jerry Walker 2011년 6월 24일
Thanks, I made the change and the program works as expected.

Siphumelele Vatsha
Siphumelele Vatsha 2023년 1월 31일
sum1 = sum1 + jfactor(r,theta,phi)*r^2*sin(theta)*dt*dp;

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by