필터 지우기
필터 지우기

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