MATLAB: Using for loops with a logical to compute means of different Names.

for loop

for example:
'A' '1'; 'B' '5'; 'C' '13'; 'B' '7'; 'A' '11'
I used the code:
a={'A' '1'; 'B' '5'; 'C' '13'; 'B' '7'; 'A' '11'}
b=str2double(a(:,2))
idx=ismember(a(:,1),'B')
out=mean(b(idx))
to find the mean of each letter ('A'. is there a for loop I can use so that I don't have to keep on manually entering 'B' in the idx=ismember(a(:,1),'B') code in order for me to receive all the means of different letters. I also have another table (unique) with all the names without repeats as on the original table there are hundreds of repeats. Pretty new to matlab. Thank you

Best Answer

M={'A' '1'; 'B' '5'; 'C' '13'; 'B' '7'; 'A' '11'}
[ii,jj,kk]=unique(M(:,1))
out=[ii accumarray(kk,(1:numel(kk))',[],@(x) {mean(str2double(M(x,2)))})]