Effacer les filtres
Effacer les filtres

How to not use a for loop

2 vues (au cours des 30 derniers jours)
Declan
Declan le 7 Sep 2022
Modifié(e) : Adam le 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.

Réponse acceptée

Adam
Adam le 7 Sep 2022
Modifié(e) : Adam le 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 commentaires
Declan
Declan le 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 le 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!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by