element wise logical operators?
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (2)
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 Kommentare
per isakson
am 13 Aug. 2012
I run
DA = rand(4,4)
DA(:,2:4)<0.5
DA(DA(:,2:4)<0.5) = 1
and get
DA =
0.5313 0.7788 0.1537 0.4574
0.3251 0.4235 0.2810 0.8754
0.1056 0.0908 0.4401 0.5181
0.6110 0.2665 0.5271 0.9436
ans =
0 1 1
1 1 0
1 1 0
1 0 0
DA =
0.5313 1.0000 1.0000 0.4574
1.0000 1.0000 0.2810 0.8754
1.0000 1.0000 0.4401 0.5181
1.0000 0.2665 0.5271 0.9436
>>
which is confusing although I understand what is happening.
I wasn't sure whether the OP wants this or something more like:
DA = rand(4,4)
tmp = DA(:,2:4);
tmp(tmp<.5) = 1;
DA(:,2:4) = tmp
per isakson
am 14 Aug. 2012
Bearbeitet: per isakson
am 14 Aug. 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!
Timj2004
am 14 Aug. 2012
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!