Will Robertson


« Earlier1 items total Later »

Don't get annoyed by gradient, et al.

In the interest of "convenience", many MATLAB functions swap the first two dimensions of a multi-dimensional array to preserve some kind of consistency with relating x-y cartesian plots and row-column matrices. At the terrible cost of great confusion in cases like the following:
%% The gradient function
%
% Consider:
%
% $$ w(x,y,z) = x + 2y + 3z $$
%
% $$ \nabla w = (1,2,3) \quad\forall x,y,z$$
%
% Let's try to do this in MATLAB:
w = zeros(5,5,5);
for x = 1:5
  for y = 1:5
    for z = 1:5
      w(x,y,z) = x + 2*y + 3*z;
    end
  end
end

[gx gy gz] = gradient(w);
grad = [gx(1) gy(1) gz(1)]

Instead, to get predictable results, do it like this:
xx = 1:5;
yy = 1:5;
zz = 1:5;
[x,y,z] = meshgrid(xx,yy,zz);

w = x + 2*y + 3*z;

[gx gy gz] = gradient(w);
grad = [gx(1) gy(1) gz(1)]

« Earlier1 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.