Search code examples
arraysmatlabmatrix-indexing

Select specific elements of an array in matlab


How to select the N elements then ignore the next N ones and then select the next N ones and so on?

foe example of the array a = 1:100;

b = 1,2,3,7,8,9,13,14,15,...


Solution

  • Approach # 1

    a1 = reshape([a zeros(1,2*N - rem(numel(a),2*N))],N,[]);
    out = reshape(a1(:,1:2:end),1,[]);
    if rem(numel(a),2*N)<N
        out = out(1:N*floor(numel(a)/(2*N)) + rem(numel(a),2*N)); %//output
    end
    

    Approach # 2

    a1 = vec2mat(a,N)'; %//'
    out = reshape(a1(:,1:2:end,:),1,[]);
    if rem(numel(a),2*N)<N
        out = out(1:N*floor(numel(a)/(2*N)) + rem(numel(a),2*N)); %//output
    end
    

    Approach # 3

    mat1 = [true false];
    mat2 = reshape(mat1(ones(N,1),:),[],1);
    mat3 = reshape(mat2(:,ones(1,ceil(numel(a)/(2*N)))),[],1);
    out = a(mat3(1:numel(a)));  %//output