Reputation: 25
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]
Upvotes: 1
Views: 2510
Reputation: 911
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
Upvotes: 0
Reputation: 1834
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, i.e. in reverse:
a=[5,4,3,2,1];
b=a(5:-1:1);
b=
1 2 3 4 5
Upvotes: 4
Reputation: 18177
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 (i.e. is it even) and use that as a logical index into a
.
Upvotes: 1