Error using piecewise function

9 次查看(过去 30 天)
Check for missing argument or incorrect argument data type in call to function 'piecewise'.
Error in D>@(i,j,h)piecewise((i-1)*h==j,1,0) (line 4)
L=@(i,j,h)piecewise((i-1)*h==j,1,0);
Error in D (line 8)
j=j+L(i,x,h)*c(i);
I'm getting this error here,
L=@(i,j,h)piecewise((i-1)*h==j,1,0); %L(i,j,h)=1 when j=(i-1)*h else 0
error is generated when it is called inside other function,
function k=D(x,c,N)
F = @(x)exp(x);
h=1/N;
L=@(i,j,h)piecewise((i-1)*h==j,1,0);
k=F(x);
for i=1:N+1
k=k+L(i,x,h)*c(i);
end
end
  1 个评论
Matt J
Matt J 2022-3-26
编辑:Matt J 2022-3-26
error is generated when it is called inside other function,
We need to know the contents of x,c, and N when this happens.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2022-3-26
When you call piecewise(), the first parameter to piecewise() must be symbolic.
Your N is very likely numeric, so your h = 1/N is likely numeric. Then when you have
for i=1:N+1
k=k+L(i,x,h)*c(i);
then i is numeric because of the for loop. So you are passing in a numeric first and third parameter to L, so in (i-1)*h==j the i and h are numeric.
We do not know the datatype of j which comes from the passed-in x so we cannot be certain in context that all parts of the test are numeric, but it seems fairly likely;.
Caution: for numeric integer N, 1/N is seldom going to be exactly representable in binary floating point, and multiplying the result by an integer might not come out exactly as an integer when you expect it to. For example,
N = 49;
h = 1/N;
N * h - 1
ans = -1.1102e-16
so 49 * (1/49 in binary floating point) does not work out as 1.
You should rarely use == to compare values computed different ways in binary floating point.
You could avoid the problem in this particular context by using h = 1/sym(N)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by