Error: "Difference order N must be a positive integer scalar"
186 ビュー (過去 30 日間)
古いコメントを表示
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 ?
0 件のコメント
回答 (2 件)
Walter Roberson
2021 年 9 月 18 日
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
2021 年 9 月 19 日
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
2021 年 9 月 18 日
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)
参考
カテゴリ
Help Center および File Exchange で Numerical Integration and Differential Equations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!