How can I create a loop for a constant value in a numerical integration problem and plot all solutions on the same graph?

7 views (last 30 days)
I have an .m-file that approximates the solution to a definite integral using Boole's rule (numerical integration).
I have a definite integral I want to approximate, with respect to theta:
f=@(theta) (1/pi)*cos(z*sin(theta)-5*(theta));
The integral has a constant value, z, in it. I want the integral to be evaluated with z values from 0-25. When I run the code I want to obtain the values of approximation with the different z values, and I also want to plot the different z values. It should look something like the Bessel function.
I know I could obtain the values by changing the z value and running the code:
f=@(theta) (1/pi)*cos(z*sin(theta)-5*(theta));
a=0;
b=pi;
z=0;
[r]=boole(f,a,b,n);
disp (r);
And then repeat the same process, only with z=1,2,3,...25.
f=@(theta) (1/pi)*cos(z*sin(theta)-5*(theta));
a=0;
b=pi;
z=1;
[r]=boole(f,a,b,n);
disp (r);
plot (r);
Can I create a for loop with the constant z-value so when I run the code it gives all of the values of the approximation with z=0 to 25? Can I then group all of these values and plot them on one graph?
Any help would be much appreciated! Thanks :)

Accepted Answer

KL
KL on 26 Sep 2017
f = @(theta) (1/pi)*cos(z*sin(theta)-5*(theta));
%your other variables
z_vec = 0:25;
for k=1:length(z)
z=z_vec(k); %pick the z for this iteration
[r{k}]=boole(f,a,b,n); %call your function
disp (r{k}); %disp results of this iteration
plot (r{k}); %plot
hold on
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!