How to split an array into two arrays?
Show older comments
Hi,
I have an array like x = [ 0:10] and need to split it into x1 = [x(0,1),x(4,5),x(8,9)] and x2 = [x1(2,3),x(6,7)]. I am able to do this by using loops but for big dara is very time consuming. Is there any other way to do this?
Thanks
5 Comments
Sindar
on 20 Jan 2020
Do you mean:
A)
x1 = [x(0),x(1),x(4),x(5),x(8),x(9)];
x2 = [x(2),x(3),x(6),x(7)];
B)
x1 = [x(0),x(1) ; x(4),x(5) ; x(8),x(9)];
x2 = [x(2),x(3) ; x(6),x(7)];
(all indexes shifted up by 1 since x(0) isn't correct in Matlab)
C) something else?
This should work for A)
x=0:10;
n = length(x);
inds_1 = [0;1] + (1:4:n-1);
x1 = x(inds_1(:));
inds_2 = [0;1] + (3:4:n-1);
x2 = x(inds_2(:));
B)
x=0:10;
n = length(x);
inds_1 = [0;1] + (1:4:n-1);
x1 = x(inds_1);
inds_2 = [0;1] + (3:4:n-1);
x2 = x(inds_2);
KSSV
on 20 Jan 2020
Note that there is no zero index in MATLAB. x(0) throws error.
Your x is an array of dimension 1x11, so using x(4,5) etc., mentioning two indices throws error. What exactly you want to do?
Stephen23
on 20 Jan 2020
Mohammad Torabi's "Answer" moved here:
Thanks for your reply, actually I did not represent the question very well, the number of items I need to extract from x is not always 2 and it is a variable and also x is a very big array. In below example, I used 10 instead of 2 for better illustration. Generally, data of x1 and x2 are stored within x alternatively like bellow:
x = [a1,a2,...,a10,b1,b2...,b10,a11,a12,...,a20,b11,b12,...,b20,a21,....]
x1 = [a1,a2,a3,...] include all a values
x2 = [b1,b2,b3,...] include all b values
Stephen23
on 20 Jan 2020
First reshape and then use indexing.
Mohammad Torabi
on 20 Jan 2020
Answers (0)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!