Vectorization of a for-loop?

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

Antworten (1)

0 Stimmen

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 Kommentar

Sebastian
Sebastian am 24 Feb. 2020
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?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2019b

Gefragt:

am 23 Feb. 2020

Kommentiert:

am 24 Feb. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by