开发者

Splitting a matrix based on its contents in MATLAB

A matrix has m rows and n columns (n being a number not exceeding 10), and the nth column contains either 1 or 0 (binary). I want to use this binary as a decision to take out the associated row (if 1, or otherwise if 0). I understand that this can be done through iteration with the use开发者_如何转开发 of the IF conditional.

However, this may become impractical with matrices whose number of rows m gets into the hundreds (up to 1000). What other procedures are available?


You can use logical datatypes for indexing. For example,

M =

 1     2     0
 4     5     1
 7     8     0
M = [1 2 0;4 5 1;7 8 0];
v = (M(:,n) == 1);
M(v,2) = 1;

M =

 1     2     0
 4     1     1
 7     8     0

Now you have set all the elements in column 2 to 1 if the corresponding element in column n is true.

Note that the v = (M(:,n) == 1) converts the nth column to a logical vector. You can accomplish the same with v = logical(M(:,n));

I would recommend this blog entry for a detailed look at logical indexing.

Update:

If you want to erase rows, then use:

M(v,:) = [];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜