Search code examples
matlabgradientboundaryderivative

Directional Derivatives of a Matrix


I have 40 structures in my Workspace. I Need to write a script to calculate the directional derivatives of all the elements. Here is the code :

[dx,dy] = gradient(Structure_element_1.value);  
dxlb = min(min(dx));  
dxub = max(max(dx));  
dylb = min(min(dy));  
dyub = max(max(dy));  

[ddx,ddy] = gradient(gradient(Structure_element_1.value));
ddxlb = min(min(ddx));  
ddxub = max(max(ddx));
ddylb = min(min(ddy));
ddyub = max(max(ddy));  

This is the code for one element. I Need to find out the same for all the 40 elements and then use it later. Can anyone help with this.


Solution

  • To answer your literal question, you should store the variables in a structure array or at least a cell array. If all of your structures have the same fields, you can access all of them by indexing a single array variable, say Structure_element:

    for i = 1:numel(Structure_element)
        field = Structure_element(i).value
        % compute gradients of field
    end
    

    Now to address the issue of the actual gradient computation. The gradient function computes an approximation for \frac{\partial F}{\partial x}, \frac{\partial F}{\partial y}, where F is your matrix of data. Normally, a MATLAB function is aware of how many output arguments are requested. When you call gradient(gradient(F)), the outer gradient is called on the first output of the inner gradient call. This means that you are currently getting an approximation for \frac{\partial^2 F}{\partial x^2}, \frac{\partial}{\partial y} \frac{\partial F}{\partial x}.

    I suspect that you are really trying to get \frac{\partial^2 F}{\partial x^2}, \frac{\partial^2 F}{\partial y^2}. To do this, you have to get both outputs from the inner call to gradient, pass them separately to the outer call, and choose the correct output:

    [dx,dy] = gradient(F);
    [ddx, ~] = gradient(dx);
    [~, ddy] = gradient(dy);
    

    Note the separated calls. The tilde was introduced as a way to ignore function arguments in MATLAB Release 2009b. If you have an older version, just use an actual variable named junk or something like that.