How can I construct a triangle function, when I tested one using 'integral(fun.-pi,pi)', error occurred.

function [a] = triangle(n)
a=zeros(size(n));
a(n>=0 & n<=pi)=pi-n;
end
--------------------
>> fun = @(x)triangle(x)
fun =
@(x)triangle(x)
>> integral(fun,-pi, pi)
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in triangle (line 3)
a(n>=0)=pi-n;
Error in @(x)triangle(x)
Error in integralCalc/iterateScalarValued (line 314)
fx = FUN(t);
Error in integralCalc/vadapt (line 132)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 75)
[q,errbnd] = vadapt(@AtoBInvTransform,interval);
Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct);
I used to define a step function like this and it works. Why did it not work this time?

 採用された回答

VBBV
VBBV 2023 年 3 月 2 日
編集済み: VBBV 2023 年 3 月 2 日
integral(@triangle,-pi,pi,'ArrayValued',1) % call function using function handle
ans = 0
function [a] = triangle(n)
a=zeros(size(n));
if a(n>=0 & n<=pi) % use an if else statement to execuete
a = pi-n;
else
a = 0; %n; % 0 otherwise
end
end

2 件のコメント

Thank you very much. I removed 'a' from the condition. Everthing works.
if (n>=0 & n<=pi) % use an if else statement to execuete
>> integral(fun,-pi,pi,'ArrayValued',1)
ans =
4.9348
May I ask one more question?
Later I try to calculate a vector y = triangle(x). It doesn't work. The argument x is a vector.
x = -pi:0.01:pi;
The result is
y = 0
---------------------------------------------------------------------------------------------
function [a] = triangle(n)
a=zeros(size(n));
if (n>=0 & n<=pi) % use an if else statement to execuete
a = pi-n;
else
a = 0; %n; % 0 otherwise
end
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by