Run a function with both input and variable

Hi!
I'm new to matlab but would like to run a script that i've tried to make somewhat readable:
syms p % degrees between 0-90
pmin = 0;
pmax = pi/2;
al = [-0.1211 -0.2005 0.1527 0.7276 0.5885 0.2645 0.6400]; %All theese values should be tested in the function giving multiple answers
fun = @(p)2.*al.*p.*sin(p).*cos(p); % the function that i want to use
alpha_stat = integral(fun,pmin,pmax) % the function will then be used in an intgral between 0-90 degrees
From this I want multiple outputs in a similar fasion to "al".
The alpha_stat outputs should be close the values of "al"

Réponses (1)

pmin = 0;
pmax = pi/2;
al = [-0.1211 -0.2005 0.1527 0.7276 0.5885 0.2645 0.6400];
fun = @(p)2.*al.*p.*sin(p).*cos(p); % the function that i want to use
To indicate that your fun is array valued you need to specify the 'ArrayValued' name-value argument with value true.
alpha_stat = integral(fun,pmin,pmax, 'ArrayValued', true)
alpha_stat = 1×7
-0.0951 -0.1575 0.1199 0.5715 0.4622 0.2077 0.5027
Without that argument being specified or if it is specified as false, integral will try to call your function with a vector of values for p (for efficiency, to reduce the number of times it needs to call the function.) In the best case scenario that p vector is incompatibly sized to be multiplied by your al vector and so you'll receive an error. If you're unlucky, it would "work" but potentially return a different answer than you expected.
alpha_stat = integral(fun,pmin,pmax)
Arrays have incompatible sizes for this operation.

Error in solution>@(p)2.*al.*p.*sin(p).*cos(p) (line 4)
fun = @(p)2.*al.*p.*sin(p).*cos(p); % the function that i want to use

Error in integralCalc/iterateScalarValued (line 314)
fx = FUN(t);

Error in integralCalc/vadapt (line 132)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);

Error in integralCalc (line 75)
[q,errbnd] = vadapt(@AtoBInvTransform,interval);

Error in integral (line 87)
Q = integralCalc(fun,a,b,opstruct);
But I want to comment on something else you wrote. When you defined the symbolic variable p (which is not necessary, as you can see from the fact that I omitted it in the code above) the comment said "% degrees between 0-90". But then in your function you used the sin and cos functions, which compute the sine and cosine of angles in radians. I believe this is correct given your limits of integration but if you intended to integrate with limits specified in degrees you'd want to use the sind and cosd functions instead of sin and cos.

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by