How to reduce matrix using array mask in MATLAB?

This seems very common to my problem:

data = [1 2 3; 4 5 6]; mask = [true false true]; mask = repmat(mask, 2, 1); data(mask) ==> [1; 4; 3; 6] 

What I wanted was [1 3; 4 6] [1 3; 4 6] .

Yes, I can just reshape to the right size, but this seems like the wrong way. Is there a better way? Why doesn't data(mask) return a matrix if it is actually rectangular? I understand that in the general case this may not be the case, but in my case, since my original mask is an array, it will always be.

Consequence

Thanks for the answer, I just wanted to point out that this also works with something that returns a numerical index like ismember , sort or unique .

I used the second return value from sort and applied it to each column manually when you can use this concept to make it one shot.

+4
source share
1 answer

This will give you what you want:

 >> data = [1 2 3; 4 5 6]; >> mask = [true false true]; >> data(:,mask) ans = 1 3 4 6 

This works because you can simply apply the logical mask index to the columns by selecting all rows with :

Even if a 2-D logical array is used for input, the output will be an array of columns with indexed values. This is because there is no guarantee that indexed elements can be organized into a two-dimensional (i.e., rectangular) output. See if your two-dimensional mask was as follows:

 mask = [true false true; true false false]; 

This will index 3 values ​​that cannot be organized into anything other than a row or column for output. Here is another example:

 mask = [true true true; true false false]; 

This will index 4 values, but 3 from the first row, and 1 from the second row. How should these values ​​be formed into a rectangular output matrix? Since there is no clear way to do this in general for an arbitrary two-dimensional index matrix, the column vector with indexed values ​​is returned.

+12
source

Source: https://habr.com/ru/post/1308388/


All Articles