Creating multiple functions using a for loop

5 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 19 May 2015
Edited: Stephen23 on 19 May 2015
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 on 20 May 2015
Edited: Matthew Brandsema on 20 May 2015
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)

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 19 May 2015
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.

Community Treasure Hunt

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

Start Hunting!