简体   繁体   中英

How do I extract the odd and even rows of my matrix into two separate matrices in scilab?

I'm very new to scilab syntax and can't seem to find a way to extract the even and odd elements of a matrix into two separate matrix, suppose there's a matrix a :

a=[1,2,3,4,5,6,7,8,9]

How do I make two other matrix b and c which will be like b=[2 4 6 8] and c=[1 3 5 7 9]

You can separate the matrix by calling row and column indices:

a=[1,2,3,4,5,6,7,8,9];
b=a(2:2:end);
c=a(1:2:end);

[2:2:end] means [2,4,6,...length(a)] and [1:2:end]=[1,3,5,...length(a)] . So you can use this tip for every matrix for example if you have a matrix a=[5,4,3,2,1] and you want to obtain the first three elements:

a=[5,4,3,2,1];
b=a(1:1:3)
b=
   1  2  3 
% OR YOU CAN USE
b=a(1:3)

If you need elements 3 to 5:

a=[5,4,3,2,1];
b=a(3:5)
b=
   3  2  1

if you want to elements 5 to 1, ie in reverse:

a=[5,4,3,2,1];
b=a(5:-1:1);
b=
  1  2  3  4  5
a=[1,2,3,4,5,6,7,8,9];
b = a(mod(a,2)==0);
c = a(mod(a,2)==1);

b =
     2     4     6     8
c =
     1     3     5     7     9

Use mod to check whether the number is divisible by 2 or not (ie is it even) and use that as a logical index into a .

The title is about selecting rows of a matrix, while the body of the question is about elements of a vector ... With Scilab, for rows just do

a = [1,2,3 ; 4,5,6 ; 7,8,9];
odd = a(1:2:$, :);
even = a(2:2:$, :);

Example:

--> a  = [
  5  4  6
  3  6  5
  3  5  4
  7  0  7
  8  7  2 ];

--> a(1:2:$, :)
 ans  =
  5  4  6
  3  5  4
  8  7  2

--> a(2:2:$, :)
 ans  =
  3  6  5
  7  0  7

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