Loop these vectors into an array?

조회 수: 1 (최근 30일)
Sean Raffetto
Sean Raffetto 2016년 2월 16일
댓글: Star Strider 2016년 2월 17일
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