필터 지우기
필터 지우기

Creating multiple functions using a for loop

조회 수: 2 (최근 30일)
Matthew Brandsema
Matthew Brandsema 2015년 5월 19일
편집: Matthew Brandsema 2015년 5월 20일
I am trying to do a numerical double integral of a summation of exponentials. The best was I can see of doing this is to use the function handles in matlab. Basically, each exponential will have the following form,
exp(i*k*R)
Where k is just a constant, i is the imaginary unit, and R is a number represented by the following form. (Just to make it easier to see for you guys. It is a distance formula, it has the following form)
R=2*sqrt(()^2+()^2+()^2). The actual code looks like this
R{i}=@(theta,phi)2*sqrt((d*cos(theta).*cos(phi)+A(i,1)).^2+(d*sin(theta)+A(i,3)).^2+(d*cos(theta).*sin(phi)+A(i,2)).^2)
Where A is a matrix of numbers. What I want to do, is create a new function (R) for each value of A, and then sum all these functions together and numerically integrate them over theta and phi using the integral2 command. here is my total code I have so far.
clc
clear all
A=csvread('Plate_Test.csv');
for i=1:3
R{i}=@(theta,phi)2*sqrt((d*cos(theta).*cos(phi)+A(i,1)).^2+(d*sin(theta)+A(i,3)).^2+(d*cos(theta).*sin(phi)+A(i,2)).^2);
end
However when I do this, matlab doesn't parse the terms like A(i,1) as anything. It simply leaves it as A(i,1) instead of using the number in the matrix A. How can I solve this problem??
  댓글 수: 3
Stephen23
Stephen23 2015년 5월 19일
편집: Stephen23 2015년 5월 19일
Note that is recommended to avoid using i and j as variable names, as these are both names of the inbuilt imaginary unit. And because you are working with complex values, it could lead to difficult to diagnose bugs... simply use other variable names and avoid the hassle!
Matthew Brandsema
Matthew Brandsema 2015년 5월 20일
편집: Matthew Brandsema 2015년 5월 20일
Okay so I will assume it is using the correct values then. I now have another problem. I want to add all the R functions together. However as I have found out, addition does not seem to be defined when working with these functions.
I need to do something like R{1}+R{2}+R{3}+....
EDIT: Ah, I realized I just need to put another function handle on it like @(theta,phi)

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

답변 (1개)

Walter Roberson
Walter Roberson 2015년 5월 19일
Although A(i,1) will show up in the function handle display, the actual value will be substituted.
If you have the Symbolic Toolkit you might want to go through creating the functions using it, and subs() in specific values, simplify() the result for efficiency, and then matlabFunction() it to get an anonymous function.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by