Vectorization of a for-loop?

11 ビュー (過去 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
Thiago Henrique Gomes Lobato 2020 年 2 月 23 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by