How to solve this problem of integeral?
2 次查看(过去 30 天)
显示 更早的评论
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
5 个评论
采纳的回答
Ameer Hamza
2020-4-24
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
0 个评论
更多回答(1 个)
Walter Roberson
2020-4-24
int is only for use with Symbolic functions or symbolic expressions. inline objects cannot be used with int.
You should only use inline if you have a very specific reason to use it. You should be using symbolic or anonymous functions instead.
However your
syms fun
on the next line overwrites fun the same as if you had done
fun = sym('fun') ;
So when you int that it is just a symbolic constant and the integral is the constant times the difference in time. Your function is going to return a symbolic expression involving the two unresolved values x and fun. x is unresolved because the
syms x
that you did overwrote the x parameter passed to the function.
so you return a symbolic expression that contains unresolved variables and outside the function you assign that into part of y. But y is double precision and you cannot store a symbolic expression with unresolved variables in double precision.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!