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 Center および File ExchangeLoops 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