Creating multiple functions using a for loop
Afficher commentaires plus anciens
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 commentaires
Joseph Cheng
le 19 Mai 2015
do you need it to display? otherwise it should still work.
A = magic(3);
disp(A)
for i=1:3
R{i}=@(gain) (A(i,1)+A(i,3)+A(i,2))*gain*i
end
R{1}(2) == sum(A(1,:))*2*1
R{2}(4) == sum(A(1,:))*4*2
R{3}(4) == sum(A(1,:))*4*3
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
le 20 Mai 2015
Modifié(e) : Matthew Brandsema
le 20 Mai 2015
Réponses (1)
Walter Roberson
le 19 Mai 2015
0 votes
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.
Catégories
En savoir plus sur Numerical Integration and Differentiation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!