# Error: "Difference order N must be a positive integer scalar"

15 views (last 30 days)
Faraz Ali on 18 Sep 2021
Commented: Walter Roberson on 19 Sep 2021
I wrote a script :
[x,y]=meshgrid(0:1:500, -100:1:100);
k=(2*pi)/30;
Q=25*k;
l=(2*pi)/30;
f=2*(cos((k*x)+Q).*cos(l*y));
xlable=('0<x<500Km');
ylable=('-100Km<y<100Km');
contourf(x,y,f,[-1,0,1]);
colorbar
and I want to calculate df/dx and plot with isoline , I added :
g = diff(f,x,1)
but this error happens after running whole script :
Error: "Difference order N must be a positive integer scalar"
what should I do ?

Walter Roberson on 18 Sep 2021
There are two different functions named diff().
Symbolic diff is calculus differentiation. It needs a symbolic expression (sym) or symbolic function (symfun) as its first parameter, and the second parameter is the variable of differentiation, and an optional third parameter is the number of times to differentiate. diff(f,x,1) would not be uncommon for that symbolic function (though diff(f,x) would be more likely perhaps.)
Numeric diff is successive numeric differences. It needs a numeric expression as the first parameter, and the second optional parameter is the number of times to take a difference, and the third optional parameter is the dimension to operate on. diff([3 8 4]) would be [8-3, 4-8] -> [5, -4] . It could potentially have the syntax diff(f,x,1) but if so then x would have to be either [] or a positive integer giving the number of times to take take the difference, and the 1 would be the dimension to operate along.
We do not advise using diff() to estimate derivatives: most of the time it is better to use gradient() instead
[gx, gy] = gradient(f, x, y);
##### 2 CommentsShowHide 1 older comment
Walter Roberson on 19 Sep 2021
diffx = diff(f,[],2);
diffy = diff(f,[],1);
gx = diffx./diff(x(1,:));
gy = diffy./diff(y(:,1));
Note that gx and gy are smaller than f is: numeric diff always shortens the array in the direction the difference is being taken. gradient() does not shorten the array.
Also note that there are mathematical reasons why using diff(f)/diff(x) does not produce the best estimate of gradient: the formula that gradient() uses is better.

Image Analyst on 18 Sep 2021
If you look at the documentation for diff() you'll see that the second argument is not a vector variable but a number for the distance (in indexes/elements) that you want to subtract. Normally it is 1. Then the third index is the direction. Since it looks like x is the second index, you want the third argument to be 2, which means go across columns.
g = diff(f,1,2)
Faraz Ali on 18 Sep 2021
I want to plot df / dx ( derivative of f(x,y) based on x ). For this purpose what shoud I do?