MATLAB: How to create a loop for a constant value in a numerical integration problem and plot all solutions on the same graph

MATLAB: How to create a loop for a constant value in a numerical integration problem and plot all solutions on the same graph

for loopintegrationnumerical integration

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 🙂

Best Answer

  • 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
  • Add a Comment

    Your email address will not be published. Required fields are marked *