arrays - Avoid loops in matlab -


i limited in use of cycles in matlab , have 1 task. have matrix 2xn numbers , cell array 1xn. each element in first row point position of array. want add every number second row of matrix cell, pointed corresponding number in first row. in addition, want cells strings.

let me clarify example:

a = [[1 4 3 3 1 4 2], [7 4 3 5 6 5 4]]

i want array of cells: {'76', '4', '35', '45'}

how can without using for or while loop?

a = [1 4 3 3 1 4 2; 7 4 3 5 6 5 4]; %// data: 2 x n array [~, ~, ii] = unique(a(1,:)); r = accumarray(ii(:),a(2,:),[],@(v) {fliplr(regexprep(num2str(v(:).'),'\s',''))}).'; 

the second line (unique) used remove possible gaps in first row. otherwise gaps translate result of accumarray, take more memory uselessly.

the third line (accumarray) aggregates values of second row of a have same value in first row. aggregation done anonymous function, converts numbers string (num2str), removes spaces (regexprep), , changes orientation (fliplr , .') match desired output format.

edit:

thanks @chappjc's suggestion, third line can simplified to

r = accumarray(ii(:),a(2,:),[],@(v) {fliplr(num2str(v(:).','%d'))}).'; 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -