MATLAB Matlab field (quiver) plot and gradient

Click For Summary
The discussion centers around an issue with the Matlab quiver plot, specifically regarding the computation of the gradient vector when using an exponential function as a velocity field. The user shares a code snippet that demonstrates how the velocity field is generated based on specified datapoints, which represent charges. The gradient is calculated using the `gradient` function, and the quiver plot is intended to visualize the resulting vector field. A key point raised is the indexing scheme used in Matlab, where the field is indexed as `field(y,x)`, which may lead to confusion when interpreting the output. The user emphasizes that understanding this indexing is crucial for accurately representing the velocity field in the quiver plot.
zslevi
Messages
8
Reaction score
0
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 interesting part is in the last loop (simtime). (It's in the attachment as well.)

Code:
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
 

Attachments

Physics news on Phys.org
Now I've got it.
Both the gradient func., both quiver plot uses the following indexing scheme:
field(y,x)