Vectorization of a for-loop?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposte (1)
Thiago Henrique Gomes Lobato
il 23 Feb 2020
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
Vedere anche
Categorie
Scopri di più su Linear Least Squares in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!