How to use gradient?
이전 댓글 표시
what is the problem with the following code?
f=input('enter function: ','s')
[DX,DY] = -gradient(f);
f = str2func(['@(x,y)' vectorize(f)]);
[DX,DY] = -gradient(f);
hold on
quiver(X,Y,DX,DY)
hold off
I get the following errors:
Error using zeros CLASSNAME input must be a valid numeric or logical class name.
Error in gradient (line 56) g = zeros(size(f),class(f)); % case of singleton dimension
채택된 답변
추가 답변 (1개)
You need to start reading the MATLAB documentation, because guessing how to use MATLAB will not be an efficient use of your time. MATLAB has very accessible documentation: learn to use it:
When you actually open the gradient documentation and read the input description, it clearly describes the first argument as "F — Input array vector | matrix | multidimensional array"
So far you have tried two different inputs, neither of which are numeric arrays:
f=input('enter function: ','s')
[DX,DY] = -gradient(f); % <- here the input is a string
f = str2func(['@(x,y)' vectorize(f)]);
[DX,DY] = -gradient(f); % <- here the input is a function handle
The gradient documentation does not state that it accepts strings or function handles. It accepts numeric data only. In fact, the subtitle at the very top of the page states quite clearly "Numerical gradient", and it does not state symbolic or functional gradient.
Perhaps you were trying to do something like this (note that this is a numeric calculation):
>> [X,Y] = meshgrid(0:9);
>> Z = X.^2 + sqrt(Y); % function of X and Y
>> [DX,DY] = gradient(Z); % input numeric array to gradient
>> quiver(X,Y,DX,DY)

댓글 수: 2
geometry geometry
2017년 5월 14일
Stephen23
2017년 5월 14일
@geometry geometry: use str2func to generate a function handle from the input string. I am sure that you can find and read the str2func documentation yourself.
카테고리
도움말 센터 및 File Exchange에서 Get Started with Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
