Vectorization of a for-loop?

2 次查看(过去 30 天)
Sebastian
Sebastian 2020-2-23
评论: Sebastian 2020-2-24
Hi everyone,
I have a part of a function, which takes measured data saved from an array (called crdvel, containing x,y,z coordinates in columns 1:3 and corresponding velocities in columns 4:6), tries to find the indices, where values i occur in another vector (valx, valy, valz), to compute a new "index", so that the velocity components of crdvel can be saved to the correct spots in matrix uvw.
n, nvx, nvy, nvz are constants, n is ~500.000, nvx/nvy/nvz ~100, valx/valy/valz are vectors of order (nvx/nvy/nvz, 1) respectively, crdvel is an array of order (n, 6), and the coordinate values repeat (example: the point x=5, y=5, z=2 exists 200 times in crdvel, with changing velocities because of measurement at different points in time)
The code works fine as is, but it takes a lot of time because of the loop so I tried to speed it up by vectorization, but failed up until now. Any help in solving this problem would be greatly appreciated!
uvw=zeros(nvx*nvy*nvz,3);
for i = 1:n
pos = crdvel(i,1:3);
x = find(valx == pos(1));
y = find(valy == pos(2));
z = find(valz == pos(3));
npos = (x-1)*nvy*nvz + (y-1)*nvz + z;
uvw(npos, 1:3) = crdvel(pos, 4:6);
end

回答(1 个)

Thiago Henrique Gomes Lobato
You're matching rows between two matrix. You can do this very efficiently using the intersect function. A dummy example:
A = [1,2,3;4,5,6;7,8,9];
B = [4,5,6;7,8,9;1,2,3];
[~,~,index_B] = intersect(A,B,'row');
index_B
B(index_B,:)
index_B =
3
1
2
ans =
1 2 3
4 5 6
7 8 9
  1 个评论
Sebastian
Sebastian 2020-2-24
Thank you for the answer. It works for the first repeats of the coordinates, though as far as I understand, intersect can't deal with repeats, so I would lose a great amount of data. Also, the dimensions of x, y and z don't fit for the following step. Do you have any further ideas on how to deal with those problems?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by