简体   繁体   中英

Combine odd and even indexes of two array columns in matlab / octave

I have an array (b) with two columns I would like to combine the data with even indexes of the second column with the data of the odd indexes of the first.
PS: the numbers won't be this linear so I can't use linspace command it's just an example.

a1=[1;2;3;4;5]
a2=[1.5;2.5;3.5;4.5;5.5]
b=[a1,a2]

b array:
1.0000   1.5000
2.0000   2.5000
3.0000   3.5000
4.0000   4.5000
5.0000   5.5000

Final output below I'm trying to get:
1
2.5
3
4.5
5

How about:

[nb_rows,nb_cols] = size(b);
c = zeros(nb_rows,1);
c(1:2:end) = b(1:2:end,1);
c(2:2:end) = b(2:2:end,2);

This handles the cases that the number of elements in a1 (and a2 ) is odd or even:

c = b.'; %'//
n = numel(a1);
ind = bsxfun(@plus, [1;4], 0:4:2*n-1);
result = c(ind(1:n)).';

您可以组合两个向量(奇数和偶数),然后对其进行排序:

c = sort([a1(1:2:end); a2(2:2:end)])

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