restate in logical indexing
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Stephen23
il 1 Feb 2017
Modificato: Stephen23
il 1 Feb 2017
>> 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 Commenti
Jan
il 1 Feb 2017
@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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!