Error using piecewise function

9 views (last 30 days)
ka
ka on 26 Mar 2022
Answered: Walter Roberson on 26 Mar 2022
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 Comment
Matt J
Matt J on 26 Mar 2022
Edited: Matt J on 26 Mar 2022
error is generated when it is called inside other function,
We need to know the contents of x,c, and N when this happens.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Mar 2022
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)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!