Error using piecewise function

7 vues (au cours des 30 derniers jours)
ka
ka le 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 commentaire
Matt J
Matt J le 26 Mar 2022
Modifié(e) : Matt J le 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.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 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)

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by