MATLAB: Array indexing with repeated index, index size larger than the array indexing Hi I want to do c = 1; for i = I B(c) = A(i); c = c + 1; end where I is a vector. For instance A = [a b c d]; I = [1 1 3 1 1 1 2 2 1]; then B = [a a c a a a b b a]; is there a fast way to do this without for loop? Thanks Best Answer One way:A = {'a' 'b' 'c' 'd'}; I = [1 1 3 1 1 1 2 2 1];B = A(I); Related SolutionsMATLAB: Elements processing in array You basically want the sum of the n-ary product of the +/- sets of each element of your array. That can be done easily with ndgrid:A = [1 3 8 2]; %demo data;sets = num2cell([A; -A], 1); %split into sets of +/- valuesnprod = cell(1, numel(A)); %create destination for n-ary product[nprod{:}] = ndgrid(sets{:}); %calculate n-ary productnprod = reshape(cat(numel(A)+1, nprod{:}), [], numel(A)); %concatenate into one matrix and reshape. Each row is one of the possible combinationsumnprod = sum(nprod, 2) %wanted result MATLAB: Indexing Are you trying to create a row vector with all the different combinations of q1, q2, q3, and q4?If so:q1=11; q2=22; q3=33; q4=44;a = [q1 q2 q3 q4];b = reshape(a(perms(1:length(a)))',[1,numel(perms(1:length(a)))]);If you would rather have a matrix of the different combinations, then:b = a(perms(1:length(a)));Or, if the order of b is really as you describe above, then use b as indices to a:b = [1 2 3 4 2 4 3 1 2 1 3 4 3 2 1 2 3 4 1 3 2 4];c = a(b); Related QuestionIndexingFor a loop , to carry out element by element multiplication is bsxfun better than conventional element by element.Logical indexingSpeed up Matrix multiplicationPreallocating a cell array of charsMatrix Indexing
Best Answer