How to not use a for loop

5 views (last 30 days)
Declan
Declan on 7 Sep 2022
Edited: Adam on 7 Sep 2022
Hi, Im trying to make a function that does the same task as below, but without using any loops (no for, if, ect.). I have looked on various links like the Vector Creation (https://au.mathworks.com/help/matlab/ref/colon.html) and Vectorisation (https://au.mathworks.com/help/matlab/matlab_prog/vectorization.html) but I still cant get it to work.
function I = intMidpointScalar(f, a, b, n)
% Add description, name, date, inputs, outputs
h = (b-a)/n;
I = 0;
for j = 1:n
x = a + (j-0.5)*h;
I = I + h*f(x);
end
With the code to call the function as:
format compact
f = @(x) sin(x).*cos(x).^2
for n = 2.^(1:6)
I=intMidpoint(f,0,pi,n);
nIntError=[n I I-2/3]
end
Currently I have the below function but I dont know where to go from here
function I = intMidpoint(f, a, b, n)
% Add description, name, date, inputs, outputs
h=0;
h = (b-a)/n;
I = 0;
l=1:n;
j=cumsum(l);
x = a + (j-0.5)*h;
I = I + f(x)*h;
Thanks in advance.

Accepted Answer

Adam
Adam on 7 Sep 2022
Edited: Adam on 7 Sep 2022
function I = intMidpointScalar(f, a, b, n)
j = 0.5:n;
h = (b-a)/n;
x = a + j * h;
I = sum( h * f(x) );
end
seems like it gives the same answer.
  2 Comments
Declan
Declan on 7 Sep 2022
Hi I tried your function and you are missing the
h=0;
h = (b-a)/n;
At the start but the rest works thankyou!
Adam
Adam on 7 Sep 2022
Oops, yes sorry, I'll edit it now. I tested on command line and didn't put all the lines consecutively as I was testing your original version too!

Sign in to comment.

More Answers (0)

Categories

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

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!