restate in logical indexing
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Stephen23
2017-2-1
编辑:Stephen23
2017-2-1
>> 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 个评论
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!