Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MATLAB Matlab field (quiver) plot and gradient

  1. Mar 31, 2010 #1
    I have been playing around with the Matlab quiver plot, and I found something strange: it seems that the gradient vector isn't computed correctly. ( I use the gradient of an exponential function as a velocity field). Please try the following code. The intresting part is in the last loop (simtime). (It's in the attachment as well.)

    Code (Text):

    clear;
    hold on
    figure(1);
    title_handle = title('cucc');
    simtime = 100;
    lenx=50;
    leny=50;
    field = zeros(lenx,leny);
    %field = randn(lenx,leny);


    d.x = 20;
    d.y = 20;
    d.width = 20;
    d.height = 10;
    datapoints(1) = d;
    % these will be the charges, or whatever

    %{
    d.x = 30;
    d.y = 10;
    d.width = 6;
    d.height = 3;
    datapoints(2) = d;

    d.x = 40;
    d.y = 25;
    d.width = 2;
    d.height = 3;
    datapoints(3) = d;
    %}

    for i=1:lenx,
        for j=1:leny,        
            dp = datapoints;      
            for k=1:length(dp),
                field(i,j) = field(i,j) + exp(-1*((dp(k).x-i)^2+(dp(k).y-j)^2)/dp(k).width^2)*dp(k).height;
            end        
        end
    end

    [DX,DY] = gradient(field,1,1);
    quiver(DX,DY);

    hold on

    rect.x=3;
    rect.y=37;
    fill([rect.x,(rect.x+1),(rect.x+1),rect.x],[rect.y,rect.y,(rect.y+1),(rect.y+1)],'g');
    ht=fill([rect.x,(rect.x+1),(rect.x+1),rect.x],[rect.y,rect.y,(rect.y+1),(rect.y+1)],'r');
    for i=1:simtime,
        ix=(round(rect.x));
        iy=(round(rect.y));
        dx = DX(ix,iy)
        dy = DY(ix,iy)
        rect.x = dx+rect.x;
        rect.y = dy+rect.y;
        X=[rect.x,(rect.x+1),(rect.x+1),rect.x];
        Y=[rect.y,rect.y,(rect.y+1),(rect.y+1)];
        set(ht,'XData',X); % redrawing the moving square
        set(ht,'YData',Y);
           
        str1 = num2str((round(rect.x)),'x:%d, ');
        str2 = num2str((round(rect.y)),'y:%d ');
        str = strcat(str1,str2)

        set(title_handle,'String',str);
        drawnow
    end
    hold off
     
     

    Attached Files:

    • fluid.m
      fluid.m
      File size:
      1.4 KB
      Views:
      70
  2. jcsd
  3. Apr 1, 2010 #2
    Now I've got it.
    Both the gradient func., both quiver plot uses the following indexing scheme:
    field(y,x)
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook