anonymous function w/ accumarray
    3 views (last 30 days)
  
       Show older comments
    
tdata = table([ 1 1 1 2 2]', [1 5 9 10 1]', 'VariableNames',{'year','id'})
  Hi 
I got error message below.  Could you help shed light why I can't use accumarray with concatinating text output?
  year    id
    ____    __
     1       1
     1       5
     1       9
     2      10
     2       1
cat = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
However got error below when trying to call
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt= accumarray( JGrp, tdata.id, [], @cat);
Error using cat
Dimension argument must be a real, positive, integer scalar.
0 Comments
Accepted Answer
  Star Strider
      
      
 on 1 Jul 2021
        Naming your function ‘cat’ overshadows the existing MATLAB function by that name, that you inadvertently called when you used the ‘@’ operator in the accumarray call.  First, rename the anonymous function, and do not use the ‘@’ in the accumarray call when calling it, since it is already a function handle.  
This slight variation on the original code works: 
tdata = table([ 1 1 1 2 2]', [1 5 9 10 1]', 'VariableNames',{'year','id'})
catfcn = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt= accumarray( JGrp, tdata.id, [], catfcn)
.
6 Comments
  Star Strider
      
      
 on 22 Aug 2022
				tdata = table([ 1 1 1 2 2]', [1 5 9 10 1]',["a" "b" "c" "d" "e"]', 'VariableNames',{'year','id','name'});
% tdata.name= cellstr( tdata.name)
tdata.name = char(tdata.name)
catfcn = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt = accumarray( JGrp, tdata.name, [], catfcn)
.
More Answers (0)
See Also
Categories
				Find more on Entering Commands in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
