How to not use a for loop

5 visualizzazioni (ultimi 30 giorni)
Declan
Declan il 7 Set 2022
Modificato: Adam il 7 Set 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.

Risposta accettata

Adam
Adam il 7 Set 2022
Modificato: Adam il 7 Set 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 Commenti
Declan
Declan il 7 Set 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 il 7 Set 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!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by