简体   繁体   中英

How can I discard some unwanted rows from a matrix in Matlab?

I have a matrix

A= [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16; 17 18 19 20]

I want to do some calculation on this matrix. But actually I do not need all the rows. So I have to discard some of the rows from the above matrix before doing a calculation. After discarding 3 rows, we will have a new matrix.

B= [1 2 3 4; 9 10 11 12; 17 18 19 20];

Now I have to use B to make some other calculations. So how can I discard some of the unwanted rows from a matrix in matlab? Any suggestion will be helpful. Thanks.

Try this: (Use when no. of rows to keep is lesser)

%// Input A
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16; 17 18 19 20];

%// Rows (1-3,5) you wanted to keep
B = A([1:3, 5],:)

Output:

B =

 1     2     3     4
 5     6     7     8
 9    10    11    12
17    18    19    20

Alternative: (Use when no. of rows to discard is lesser)

%// rows 2 and 3 discarded
A([2,3],:) = [];

Output:

>> A

A =

 1     2     3     4
13    14    15    16
17    18    19    20

Note: Here (in the alternate method), the output replaces the original A . So you need to back up A if you need it afterwards. You could do this before discarding operation to backup Input matrix

%// Input A is backed up in B
B = A;

You can select the indices of the rows you want to keep:

A([1,3,5],:)

ans =

     1     2     3     4
     9    10    11    12
    17    18    19    20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM