Reputation: 1453
I have a problem : suppose I have a matrix
A =
-1 2 -3
-4 5 -6
-7 8 -9
I convert it into a column matrix
B = A(:)
B =
-1
-4
-7
2
5
8
-3
-6
-9
Suppose I want to force the first column elements to lie within a particular range (-range1 : range1) , second column elements within (-range2 : range2) & third column elements within (-range3:range3). I tried doing that by implementing this code :
range1 = 0;
range2 = -5;
range3 = 0;
B(B(1:3,1)<range1)=10;
B(B(4:6,1)>range2)=0;
B(B(7:9,1)<range3)=20;
The answer I get is this :
B =
20
20
20
2
5
8
-3
-6
-9
Whereas the correct answer I should get is this :
B =
10
10
10
0
0
0
20
20
20
What I am doing wrong ? Please help.
Upvotes: 0
Views: 1170
Reputation: 76927
You can do this:
A=[-1,2,-3;-4,5,-6;-7,8,-9];
range1 = 0;range2 = -5;range3 = 0;
B=A;
B((B(:,1)<range1),1)=10;
B((B(:,2)>range2),2)=0;
B((B(:,3)<range3),3)=20;
Output B is in mxn dimension as your A.
If you want it as column vector.
B=B(:);
Upvotes: 1
Reputation: 114816
Look closely at your command:
>> B( B(7:9, 1) < range3 ) = 20;
And now let's do it step by step
You are conditioning on the last three elements B( 7:9, 1 )
which are -3, -6
and -9
.
Therefore you end up with
>> B(7:9, 1) < range3
ans =
true
true
true
You have a logical indexing of three elements. Using these logical indices to access B
, which has 9 elements result with an access to the first three elements out of nine.
Thus, all your commands only modifes the first three elements of B
without affecting the rest of B
.
You can actively define the range you are working on, for example, the second column:
>> aRange = 4:6;
>> B( aRange( B(aRange, 1) > range2 ) ) = 0
See how the three-vector logical indexing B(aRange, 1) > range2 )
now index aRange
(which has 3 elements) and not B
(which has 9 elements) directly.
Upvotes: 1