How to assign indexes to a function handle?

309 Views Asked by At

I'm trying to approximate the integral of the functions "fun_1" and "fun_2" over the given region. In the case of one single "f" it seems ok. But I want to use a vector "f" instead of a single value to have a vector of "TL" values. I don't know how to handle this problem. The code is:

gamma = 1.4;
R = 286;
T = 273.15;
c_1 = sqrt(gamma*R*T);
c_2 = c_1
h = 0.00163;
rho_s = 2750;
M = 0;
m = rho_s*h;
eta = 0.01;
E = 72e9;
v = 0.30;
D = E*h^3/(12*(1-v^2));
f_c1 = c_1^2/(2*pi)*(m/D)^0.5;
f_c2 = c_2^2/(2*pi)*(m/D)^0.5;
n = 1500;
f = linspace(55,7700,n);
for i=1:numel(f)
    omega(i) = 2*pi*f(i);
    phi_2 = @(phi_1,beta) acos(c_2/c_1.*cos(phi_1).*(1+M.*cos(beta).*cos(phi_1)).^-1);
    tau = @(phi_1,beta) ((0.5*(rho_2*c_2/(rho_1*c_1))^0.5...
        +0.5*(rho_1*c_1/(rho_2*c_2))^0.5*sin(phi_2(phi_1,beta))./(sin(phi_1).*(1.0...
        +M*cos(beta).*cos(phi_1)))+0.5*eta*m*omega(i)*(rho_1*c_1*rho_2*c_2)...
        ^-0.5.*(f(i)/f_c2).^2.*sin(phi_1).*cos(phi_2(phi_1,beta)).^4).^2).^-1;
    fun_1 = @(phi_1,beta) tau(phi_1,beta).*sin(phi_1).*cos(phi_1);
    q_1(i) = integral2(fun_1,12*pi/180,90*pi/180,0,2*pi);
    fun_2 = @(phi_1,beta) sin(phi_1).*cos(phi_1);
    q_2 = integral2(fun_2,12*pi/180,90*pi/180,0,2*pi);
    tau_avg = q_1/q_2;
    TL = -10*log10(tau_avg);
end
2

There are 2 best solutions below

6
Ander Biguri On

use a cell array. TL{i}=-10*log10(tau_avg);

0
Mohammad Sd On

I received this answer from a user in MATLAB Answers that worked for me and solved my problem. So the vectorized version compared to the loop is more efficient.

... the integral2 function cannot integrate arrays, although integral can. The way to deal with that problem with respect to a double integral is essentially:

f = randn(1, 25);
fcn = @(x,y) sin(2*pi*f.*x) .* exp(0.1*f.*y);
int2 = integral(@(y) integral(@(x) fcn(x,y), 0, 1, 'ArrayValued',1), -1, 0, 'ArrayValued',1);

This returns a vector the size of f.