How to not use a for loop

조회 수: 6 (최근 30일)
Declan
Declan 2022년 9월 7일
편집: Adam 2022년 9월 7일
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.

채택된 답변

Adam
Adam 2022년 9월 7일
편집: Adam 2022년 9월 7일
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
Declan
Declan 2022년 9월 7일
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 2022년 9월 7일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by