MATLAB: How Gradient is calcuted

matlab basics

In matlab i have found following answers. let X =
1 2 3
3 4 5
3 2 1
z=gradient(X)
z =
1 1 1
1 1 1
-1 -1 -1
[z,c]=gradient(X)
z =
1 1 1
1 1 1
-1 -1 -1
c =
2 2 2
1 0 -1
0 -2 -4
But how z and c is calculated,what z and c indicates.

Best Answer

Hi Tinkul,
It is probably clearer if you call your variables z and c different names such as dx and dy. This is because the first and second outputs from gradient is the gradient in each of those directions.
So if you have:
M =
1 2 3
3 4 5
3 2 1
[dx,dy]=gradient(M)
dx =
1 1 1
1 1 1
-1 -1 -1
dy =
2 2 2
1 0 -1
0 -2 -4
You'll notice that dx(1,:) is almost the same as diff(M(1,:)), and dy(:,1) is almost the same as diff(M(:,1)). The main difference is that gradient replicates the last result so that the output has the same size as the input.
Update: this is not quite correct. The two-sided gradient is used in gradient... the one-sided gradient is used in diff.
Does that help? You can also check out the help for gradient which says even more.