Help me vectorize this code

6 Ansichten (letzte 30 Tage)
VisLab
VisLab am 7 Nov. 2013
Bearbeitet: Andrei Bobrov am 8 Nov. 2013
for x=1:1:rows
for y=1:1:cols
RE_p(y,x) = RE(y,x,bestori_map(y,x));
RO_p(y,x) = RO(y,x,bestori_map(y,x));
end
end
- RE, RO: arrays of size cols*rows*8;
- bestori_map: array of size cols*rows;
what is the best way (and/or fastest) to vectorize this piece of code withouth the need of for cycles ?
Thank you
  2 Kommentare
Cedric
Cedric am 7 Nov. 2013
Bearbeitet: Cedric am 7 Nov. 2013
What are RE, RO, and bestori_map?
VisLab
VisLab am 8 Nov. 2013
Bearbeitet: VisLab am 8 Nov. 2013
RE, RO - arrays of size cols*rows*8
bestori_map - array of size cols*rows

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 8 Nov. 2013
s = size(RE);
[ii,jj] = ndgrid(1:s(1),1:s(2));
ij = sub2ind(s,ii(:),jj(:),bestori_map(:));
RE_p = reshape(RE(ij),s(1:2));
RO_p = reshape(RO(ij),s(1:2));
  1 Kommentar
VisLab
VisLab am 8 Nov. 2013
Works like a charm!
If you'd care to briefly explain the process it would be awesome.
Thank you very much :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 7 Nov. 2013
Bearbeitet: Andrei Bobrov am 8 Nov. 2013
[X, Y] = ndgrid(1:rows, 1:cols);
X = X(:);
Y = Y(:);
Z = reshape( bestori_map(1:rows,1:cols), [], 1);
linidx = sub2ind(size(RE), X,Y, Z);
RE_p(1:rows,1:cols ) = reshape(RE(linidx),rows, cols );
linidx = sub2ind(size(RO), X, Y, Z);
RO_p(1:rows,1:cols) = reshape(RO(linidx),rows, cols, );
Note: if RE and RO are the same size then you can re-use linidx instead of re-calculating it.
  4 Kommentare
Andrei Bobrov
Andrei Bobrov am 8 Nov. 2013
Hi VisLab! Your RO and RE - functions or arrays?
VisLab
VisLab am 8 Nov. 2013
arrays of cols*rows*8 size (RE,RO) and cols*rows (RE_p,RO_p, bestori_map), respectively.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by