Loop these vectors into an array?

1 次查看(过去 30 天)
I have a function that needs to be integrated.
int = @(x)(1+0.25*sin((P/5)*x*sin(AngRad)+(P/4))).*exp(-1i*2.*x.*cos(AngRad).*K(1));
q01 = integral(int,-L/2,L/2,'ArrayValued',true);
int = @(x)(1+0.25*sin((P/5)*x*sin(AngRad)+(P/4))).*exp(-1i*2.*x.*cos(AngRad).*K(2));
q02 = integral(int,-L/2,L/2,'ArrayValued',true);
%this goes on 35 more times
The value "P" is pi just with more digits, "AngRad" is a 721x1 vector of angles 0-360 degrees in radians, and "K" is originally a 37x1 vector of wave numbers. My goal is to find a way to loop (or some other way) the function and the integral so that I don't have to have 37 different "q01" to form my ultimate matrix which is a 721x37 matrix, a combination of the AngRad and K vectors. How and what is the best way to go about this and save computation time?

采纳的回答

Star Strider
Star Strider 2016-2-17
I would just index it into a loop:
intfcn = @(x,Kv)(1+0.25*sin((P/5)*x*sin(AngRad)+(P/4))).*exp(-1i*2.*x.*cos(AngRad).*Kv);
for k1 = 1:37
q(:,k1) = integral(@(x)intfcn(x,K(k1)), -L/2,L/2, 'ArrayValued',true);
end
This is UNTESTED CODE (since I can’t test it), but should produce the matrix ‘q’ that you want. It changes your ‘intfcn’ function slightly (I changed its name because int is the Symbolic Math Toolbox integral function, and ‘overshadowing’ built-in MATLAB functions is to be avoided), but you also don’t have to re-define it in the loop each time, so it should be a bit more efficient as well.
  2 个评论
Sean Raffetto
Sean Raffetto 2016-2-17
This loop does work, even though it's outputting the wrong matrix values. Thank you.
Star Strider
Star Strider 2016-2-17
My pleasure!
I’m not quite certain what function you’re integrating (so I’m not certain how much this will help), but when in doubt, vectorise everything as a first step, unless you want matrix — rather than array — operations:
intfcn = @(x,Kv) (1+0.25.*sin((P/5)*x.*sin(AngRad)+(P/4))).*exp(-1i*2*x.*cos(AngRad).*Kv);

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2016-2-17
tic;
P = 3.14159265358979323846264338328;
AngRad = linspace(0,2*pi,721);
K = round(linspace(380,650,37));
L = sqrt(1/5); %for lack of better value
[RadR, KR] = ndgrid(AngRad, K);
int = @(x) (1+0.25.*sin((P/5).*x.*sin(RadR)).*(exp(-1i.*2.*x.*cos(RadR).*KR)));
q = integral(int, -L/2,L/2, 'ArrayValued', true);
toc
size(q)
Elapsed time is 1.986690 seconds.
ans =
721 37

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by