How can I average the vectors within the grid cell?

Hi altruists,
Suppose, I generated this simple vetor field using these few lines of codes:
[X,Y] = meshgrid(0:6,0:6);
U = 0.25*X;
V = 0.5*Y;
[Xq,Yq] = meshgrid(-6:0.25:6);
Uq = interp2(X,Y,U,Xq,Yq);
Vq = interp2(X,Y,V,Xq,Yq);
figure,
quiver(Xq,Yq,Uq,Vq,'autoscale','on');
grid on
title('Vector field','fontweight','bold', 'fontsize',20);
So, I get this grid -
Now - without considering 'all' these vectors, I simply want to take only one vector from each of the grid cell. The vector should be the average of all the vectors within that grid cell. The outcome should be like this -
So, the each of the grid cell is containing only one 'averaged' vector. In picture, it's shown in red (the value is exaggerated). Ciould you please give me an idea on how can I possibly do it?

 採用された回答

Turlough Hughes
Turlough Hughes 2022 年 2 月 7 日

0 投票

% code provided in the question
[X,Y] = meshgrid(0:6,0:6);
U = 0.25*X;
V = 0.5*Y;
[Xq,Yq] = meshgrid(0:0.25:6);
Uq = interp2(X,Y,U,Xq,Yq);
Vq = interp2(X,Y,V,Xq,Yq);
figure,
quiver(Xq,Yq,Uq,Vq,'autoscale','on');
grid on
title('Vector field','fontweight','bold', 'fontsize',20);
axis equal
You could block process the data taking the averages of each block as follows
m = 5; n = 5;
f = @(D,m,n) blockproc(D,[m n],@(block_struct) mean(block_struct.data,'all'));
Xd = f(Xq,m,n);
Yd = f(Yq,m,n);
Ud = f(Uq,m,n);
Vd = f(Vq,m,n);
hold on, quiver(Xd,Yd,Ud,Vd,'Color','red')
Is that what you meant?

3 件のコメント

Ashfaq Ahmed
Ashfaq Ahmed 2022 年 2 月 7 日
Hi @Turlough Hughes that is a wonderful response. Thank you so much for it. Honestly, I wanted something like that, but I have two confusions. 1. I was actually expecting the red arrows to be starting from the center of every cell. 2. The red arrows need to be of the average value of all the vectors in that particular cell (the resultant red arrows look greated in size). Could you please give me an idea on how can I modify your code a little?
Ashfaq Ahmed
Ashfaq Ahmed 2022 年 2 月 7 日
(correction)
Oh, I understand why did it happen. It's because of the nature of the vector field itself. Because the field has more value the more it goes to the right/up. So, the average value's arrow shifts frm the center point.
Turlough Hughes
Turlough Hughes 2022 年 2 月 7 日
The red arrows start at the center of groups of 5 by 5 blue vectors from the original plot, and the undelying data defining the red vectors is in fact the average from those 5 by 5 vector groups. However, the plot is very misleading in that regard because the vectors were autoscaled by quiver(). Make sure to turn 'autoscale','off', if you want to compare the two plots.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVector Fields についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by