Error using piecewise function

조회 수: 3 (최근 30일)
ka
ka 2022년 3월 26일
답변: Walter Roberson 2022년 3월 26일
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