restate in logical indexing

1 次查看(过去 30 天)
Amy
Amy 2017-2-1
评论: Jan 2017-2-1
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!

采纳的回答

Stephen23
Stephen23 2017-2-1
编辑:Stephen23 2017-2-1
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;
  2 个评论
Amy
Amy 2017-2-1
Thank you very much!
Usually 'find' is not recommended for computational efficiency, if I recall correctly.
Because of your answer I thought of the possibility of using 'reshape' to compute the linear indices.
I am not sure which method would be most efficient computationally.
Jan
Jan 2017-2-1
@Amy: If you can solve a problem using logical indexing, find wastes time usually. But here find is used to obtain the row indices. You can try which version is faster for your data.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by