Reputation: 63
I need to divide a vector into two equal vector in MATLAB. Could you help me please?
For example if I have the vector x=[1 3 7 9]
and I need two split it into y=[1 3]
and z=[7 9]
.
Upvotes: 1
Views: 3575
Reputation: 14939
end
is a clever command in MATLAB that can be used as a shortcut in many situations, for instance when you want to take only the first half of a vector, like this:
v(1:end/2);
You can split a vector into two by using deal
in an anonymous function handle:
split_vec = @(x) deal(x(1:floor(end/2)), x(floor(end/2)+1:end));
[a, b] = split_vec(1:10)
a =
1 2 3 4 5
b =
6 7 8 9 10
Upvotes: 0
Reputation: 1164
I would recommend to check out some basic matlab operations.
if you take vector x
x=1:1000;
you can easily split him into different new arrays. If you want to have to arrays with the same length you should use numel()
or size()
to get the size and then take half of it.
length_of_x=numel(x);
new_length=ceil(length_of_x/2);
I used ceil()
(rounding up) in case your x has not the length: 2,4,6,8 and so on but 1,3,5... Then you can use 1:new_length
to get the first half and new_length+1:end
for the later half.
x1=x(1:new_length);
x2=x(newlength+1:end);
would be the result for your task.
Upvotes: 2
Reputation: 3364
function [v1, v2] = DivideVectorIntoTwo (v)
midindex = floor (length (v) / 2) ;
v1 = v (1:midindex) ;
v2 = v (midindex+1 :end) ;
end
Upvotes: 5