MATLAB: How to solve this problem of integeral

integralintegrationnumerical integration

Can anypody help with this piece of code?
The problem is with the use of the integeral function
%------------------------------------------------------------------------%

clear variables;
close all;
clc;
%------------------------------------------------------------------------%
x=-1:0.1:1;
n=length(x);
y=zeros(1,n);
for i=1:n
y = m_cost(x);
end
plot(y)
and here is my function:
function y =m_cost(x)
fun1=inline('0-x','x');
fun2=inline('x-4','x');
syms fun1;
syms fun2;
syms x;
if (x>=0)
y=x.^2+4*x+8*int(fun1,x,0,10);
else
y=x.^2+4*x+8*int(fun2,x,0,10);
end

Best Answer

There is no need to use inline. You can use an anonymous function. Also, int() is used for symbolic integration. Here you can use numeric integration using integral(). The function can be vectorized so there is no need to use a for-loop
%------------------------------------------------------------------------%

clear variables;
close all;
clc;
%------------------------------------------------------------------------%
x = -1:0.1:1;
n = length(x);
y = m_cost(x);
function y =m_cost(x)
fun= @(x) -x;
y = x.^2+4*x+8*integral(fun,0,10);
end
Related Question