3

Forcing limits on a matlab vector

 3 years ago
source link: https://www.codesd.com/item/forcing-limits-on-a-matlab-vector.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Forcing limits on a matlab vector

advertisements

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.


What is wrong:

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.

A possible fix:

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK