element wise logical operators?
26 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a question regarding using logical operators on a multi-dimensional array.
I want to firstly test if an element passes a criteria then replace that value with another value given the results of a test.
I want to check the first dimension of the array against the threshold of 0.5 and replace all instances where this is true with a value for only 2 columns of the the 2nd dimension and all cases of the 3rd and 4th dimension. Does anyone know how to do this without multiple for loops?
for example
DA = rand(4,4,2,3);
if DA(:,2:4,:,:)<0.5;
DA(:,2:4,:,:) = 1;
end
thanks Tim
0 commentaires
Réponse acceptée
Azzi Abdelmalek
le 14 Août 2012
Modifié(e) : Azzi Abdelmalek
le 14 Août 2012
clear
DA = rand(4,4,2,3);
K=arrayfun(@(x) x<0.5,DA(:,2:4,:,:))
B=DA(:,2:4,:,:);
B(find(K==1))=1;
DA(:,2:4,:,:)=B
1 commentaire
per isakson
le 14 Août 2012
Modifié(e) : per isakson
le 14 Août 2012
Explicitly operating on a sub array and assign it back is a good approach. However, may I propose a bit of refactoring according to Matt Fig above:
sub_array = DA(:,2:4,:,:);
sub_array( sub_array < 0.5 ) = 1;
DA(:,2:4,:,:) = sub_array;
Plus de réponses (2)
Matt Fig
le 13 Août 2012
Modifié(e) : Matt Fig
le 14 Août 2012
Do you mean this?
DA = rand(4,4,2,3);
DA(DA(:,2:4,:,:)<0.5) = 1;
or perhaps you are talking about this (see the comments below):
DA = rand(4,4,2,3);
tmp = DA(:,2:4,:,:);
tmp(tmp<.5) = 1;
DA(:,2:4,:,:) = tmp;
3 commentaires
per isakson
le 14 Août 2012
Modifié(e) : per isakson
le 14 Août 2012
It turned out, I cannot make sense of the question. OP must help.
However, I found it very hard to grasp
M( logical_index ) = scalar;
when size(M) is not equal to size(logical_index). One dimension is ok, but four is not.
Is there a way to think about it?
OK, now I got the message: Work with sub arrays!
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!