MATLAB: Restate in logical indexing

logical indexing

Dear all,
How could I restate the following code using logical indexing?
for kk=1:rxnumber %columns
for ll=1:jj %rows
if A(ll,kk)>0
C(ll,A(ll,kk))=B(ll,kk);
end
end
end
What does this code do:
If I have matrices
A= [ 0 0 7; 0 5 0; 0 0 0; 0 0 0];
B= [ 0 0 0.2; 0 0.3 0; 0 0 0; 0 0 0];
Then I would like to produce the following matrix:
C= [0 0 0 0 0 0 0.2; 0 0 0 0 0.3 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0];
Or:
C=zeros(4,7);
B(1,3)--> C(1,7).
B(2,2)--> C(2,5).
Why do I find it hard to figure out a logical indexing code myself: if the value in A is zero, then nothing should happen. I don't know how to write a code where the 0 values are ignored.
A solution that is not elegant would be:
C=zeros(4,max(max(A))+1).
A(A==0)=max(max(A))+1.
Followed by:
C(:,A(:,:))=B(:,:).
C(:,8)=[];
Which realizes:
C= zeros(4,8).
A= [ 8 8 7; 8 5 8; 8 8 8; 8 8 8];
C= [0 0 0 0 0 0 0.2; 0 0 0 0 0.3 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0];
How can I make an elegant solution for this?
Thank you in advance!

Best Answer

One way would be to use sub2ind, which generates linear indices (not logical indices):
>> A = [0,0,7; 0,5,0; 0,0,0; 0,0,0];
>> B = [0,0,0.2; 0,0.3,0; 0,0,0; 0,0,0];
>> X = A>0;
>> [R,~] = find(X);
>> C = zeros(size(B,1),max(A(X)));
>> C(sub2ind(size(C),R,A(X))) = B(X)
C =
0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.20000
0.00000 0.00000 0.00000 0.00000 0.30000 0.00000 0.00000
0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000
0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000
If you really want to use logical indices, then you can use the same method to create a logical array:
L = false(size(B,1),max(A(X)));
L(sub2ind(size(L),R,A(X))) = true;