Loop these vectors into an array?

1 visualizzazione (ultimi 30 giorni)
Sean Raffetto
Sean Raffetto il 16 Feb 2016
Commentato: Star Strider il 17 Feb 2016
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?

Risposta accettata

Star Strider
Star Strider il 17 Feb 2016
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 Commenti
Sean Raffetto
Sean Raffetto il 17 Feb 2016
This loop does work, even though it's outputting the wrong matrix values. Thank you.
Star Strider
Star Strider il 17 Feb 2016
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);

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 17 Feb 2016
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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by