Indexing irregular, constant width "stripes" of a 2-d array

1 visualización (últimos 30 días)
Knut
Knut el 18 de Nov. de 2016
Comentada: Knut el 18 de Nov. de 2016
I want to index an array in asynchronous stripes of constant width. Perhaps best described by an example:
bob = magic(7);
w = 2;
c = [1 3 6];
r = [1 4 3];
for stripe = 1:length(c)
res(stripe,:) = bob(r(stripe), c(stripe)+(0:w-1));
end
bob =
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
res =
30 39
16 25
35 37
Can the experts recommend a way to generally express this that is compact, readable and fast?
  1 comentario
KSSV
KSSV el 18 de Nov. de 2016
Not clear, you want to extract elements with a common difference/ width? Check res, the difference is 9,9,2.

Iniciar sesión para comentar.

Respuestas (1)

Walter Roberson
Walter Roberson el 18 de Nov. de 2016
Anything much different than that stops being as readable.
You could think in terms of calculating the linear indices of the sources using sub2ind. Once you have that then you can see how the entire source could be vectorized, and if the destination does not exist (or is being completely overwritten) you could construct the destination with reshape() instead of sub2ind for that.
You could then take the step of bringing the sub2ind inline. For 2d arrays it is ((row_number-1)*number_of_rows+column_number)
That would increase your speed. But it is less readable.
  1 comentario
Knut
Knut el 18 de Nov. de 2016
Yes, I was thinking along those lines. Doing the sub2ind thing manually, exploiting the "outer sum" feature of recent MATLAB implicit expansion:
[ht,wd] = size(bob);
id2 = (c-1).*ht+r;
bob(id2+ht*(0:w-1)')'
one-liner (giving the transpose of the reference):
bob(((c-1)+(0:w-1)')*size(bob,1)+r)
But I agree, this code will be fast, but it:
1. Will be as comprehensible to general programmers as LISP is to me
2. Won't run on MATLAB 2016a or older

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by