MATLAB Answers

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

조회 수: 18(최근 30일)
Faraz Ali
Faraz Ali 2021년 9월 18일 15:16
댓글: Walter Roberson 2021년 9월 19일 8:56
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 ?

답변(2개)

Walter Roberson
Walter Roberson 2021년 9월 18일 15:38
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
Walter Roberson
Walter Roberson 2021년 9월 19일 8:56
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
Image Analyst 2021년 9월 18일 15:34
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)
  댓글 수: 1
Faraz Ali
Faraz Ali 2021년 9월 18일 20:06
I want to plot df / dx ( derivative of f(x,y) based on x ). For this purpose what shoud I do?

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by