2
votes

I have a 2 dimensional array L, and I am trying to create a vector of linear indices ind for each row of this array.

L=
1 5 25 4 0 0 
2 3 3 45 5 6
45 5 6 0 0 0

I am using lenr to store the number of non zero elements in each row (starting from column 1).

lenr=
4
6
3

Then I have 1x45 array RULES. Indices stored in L refer to elements in RULES. Since I want to vectorize the code, I decided to create linear indices and then run RULES(ind).

This works perfectly:

ind=sub2ind(size(L),1,lenr(1));

while this doesn't work:

ind=sub2ind(size(L),1:3,1:lenr(1:3));

Any ideas?

UPDATE:

This is what I initially tried to vectorize the code, but it did not works and that's why I checked linear indices:

rul=repmat(RULES,3);
result = rul((L(1:J,1:lenr(1:J))));
1
Please provide a complete example and explain what you're trying to do.excaza
@excaze: Look my updates.Klausos Klausos
Why are you using 1:lenr(1:3) instead of lenr(1:3)?excaza
@excaza: I use 1:lenr(1:3) in order to get L elements FROM 1 TO the corresponding length for each row (lenr contains lengths excluding 0s).Klausos Klausos
Here let me feed you - allind = reshape(1:numel(L),size(L,1),[]) and then ind = allind(L~=0). Not tested though.Divakar

1 Answers

0
votes

If I correctly interpret your edit, you want to create a variable result that contains the elements of RULES indicated by the non-zero elements of L. Note that in general, the best way to vectorize sub2ind is to not use sub2ind.

If you want result to be a linear array, you can simply write

%// transpose so that result is ordered by row
L_transposed = L.'; 
result = RULES(L_transposed(L_transposed>0));

If, instead, you want result to be an array of the same size as L, with all numbers in L replaced by the corresponding element in RULES, it's even simpler:

result = L;
result(result>0) = RULES(result>0);