Manually determining the gradient of a surface
Show older comments
Hi , I’m trying to write a function that can manually determine the gradient of a surface (represented by a multivariable function that I have created) at a particular point (x,y)
The code I've written is shown below.
function [pdx,pdy] = comp_gradient(x,y)
kernelx = [2.5,0,-2.5];
kernely = [2.5;0;-2.5];
z = cos(x/2).* cos(y) + (y/10) - (x/5);
pdx = conv2(kernelx,z,'same');
pdy = conv2(kernely,z,'same');
end
I'm not sure where to go from here, my output is clearly incorrect.
Any help would be greatly appreciated.
Accepted Answer
More Answers (2)
Alexander Viktorov
on 2 Jan 2019
% Hi , I’m trying to write a function that can manually determine
% the gradient of a surface (represented by a multivariable
% function that I have created) at a particular point (x,y)
% The code I've written is shown below.
function [pdx, pdy] = comp_gradient(x, y, h)
% fun - char of function (ToDo)
% x - scalar numeric
% y - scalar numeric coordinates of a particular point (x,y)
% h - step of each argument (the less h the greater precision)
% % % kernelx = [2.5,0,-2.5];
% hx = 2.5; % step of argument x
% kernelx = -2.5:hx:2.5;
n = 5; % for example
kernelx = (x - n*h):h:(x + n*h);
% % % kernely = [2.5;0;-2.5];
kernely = (y - n*h):h:(y + n*h);
[X, Y] = meshgrid(kernelx, kernely);% since (kernely == kernelx)
% % % z = cos(x/2).* cos(y) + (y/10) - (x/5);
z = cos(X/2).* cos(Y) + (Y/10) - (X/5);
% [pdx, pdy] = gradient(z, hx, hx);
[px, py] = gradient(z, h, h)
% returns a matrix (2n+1)by(2n+1) for each gradient's component
% take the result from center
pdx = px(n+1, n+1);
pdy = py(n+1, n+1);
% % % pdx = conv2(kernelx,z,'same');
% % % pdy = conv2(kernely,z,'same');
end
% I'm not sure where to go from here,
% my output is clearly incorrect.
% Any help would be greatly appreciated.
%comp_gradientTest.m - Тестирование comp_gradient
% This script was generated by the AlVi Toolbox version 0.2.0.00
% development: 02-Jan-2019 23:48:05
clc; clear; close all;
format compact
name = 'comp_gradient' % имя тестируемой функции
disp('====== test of [pdx, pdy] = comp_gradient(x, y, h) ======')
x = 1
y = 3
h = 0.1
[pdx, pdy] = comp_gradient(x, y, h)
disp('== complete testd of comp_gradient ===')
help 'comp_gradient'
loc = which('comp_gradient')
% [fList, pList] = matlab.codetools.requiredFilesAndProducts('comp_gradient.m')
% shg %show graph window current
commandwindow
Puro89
on 22 Nov 2019
0 votes
Hi, how can I deal with the gradient of a image? I have this exercise that expressively ask to use the "conv2" function. Thanks in advance.
Categories
Find more on 3-D Function Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!