필터 지우기
필터 지우기

anonymous function w/ accumarray

조회 수: 1 (최근 30일)
Pete sherer
Pete sherer 2021년 7월 1일
댓글: Star Strider 2022년 8월 22일
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.

채택된 답변

Star Strider
Star Strider 2021년 7월 1일
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'})
tdata = 5×2 table
year id ____ __ 1 1 1 5 1 9 2 10 2 1
catfcn = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt= accumarray( JGrp, tdata.id, [], catfcn)
tt = 2×1 cell array
{'1,5,9'} {'10,1' }
.
  댓글 수: 6
Pete sherer
Pete sherer 2022년 8월 22일
편집: Pete sherer 2022년 8월 22일
I tried using the cellstr() to apply to the string-type variable before using the step above but it didn't work.
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);
catfcn = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt = accumarray( JGrp, tdata.name, [], catfcn)
Error using accumarray
Second input VAL must be a full numeric, logical, or char vector or scalar.
Star Strider
Star Strider 2022년 8월 22일
It doesn’t work because it remains a cell array. Use the char function instead —
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)
tdata = 5×3 table
year id name ____ __ ____ 1 1 a 1 5 b 1 9 c 2 10 d 2 1 e
catfcn = @(x) {sprintf([repmat('%s,',1,length(x)-1) '%s'], string(x))};
[ uniqYr,~,JGrp] = unique( tdata(:,'year'));
tt = accumarray( JGrp, tdata.name, [], catfcn)
tt = 2×1 cell array
{'a,b,c'} {'d,e' }
.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by