joining string variables in a table with strjoin and rowfun
조회 수: 16 (최근 30일)
이전 댓글 표시
Hey all,
I'm trying to concatenate strings stored in table variables together using strjoin and rowfun. Seems liek this should be a pretty trivial problem, but I'm having trouble.
Here's what I'm trying to do
a = [1;2;3];
b = {'one'; 'two'; 'three'};
c = {'uno'; 'dos'; 'tres'};
T = table(a,b,c)
rowfun(@(aa, bb) {strjoin({aa,bb}, '_')}, T, 'InputVariables', {'b', 'c'})
This gives an error however:
Error using table/rowfun>dfltErrHandler (line 310)
Applying the function '@(aa,bb){strjoin({aa,bb},'_')}' to the 1st row of A generated the following
error:
First input must be a 1xN cell array of strings.
Error in table/rowfun>@(s,varargin)dfltErrHandler(grouped,funName,s,varargin{:}) (line 197)
errHandler = @(s,varargin) dfltErrHandler(grouped,funName,s,varargin{:});
Error in table/rowfun (line 215)
[b_data{i,:}] = errHandler(struct('identifier',ME.identifier, 'message',ME.message,
'index',i),inArgs{:});
The error ` First input must be a 1xN cell array of strings ` is clearly from strjoin not getting the right input, but I'm not sure why. I thought itm ight be my use of {} in the function so I rewrote it like this:
rowfun(@(aa, bb) {strjoin(cell(aa,bb), '_')}, T, 'InputVariables', {'b', 'c'})
But now it gives a different error:
'Conversion to double from cell is not possible.'
If I try to run it outside of rowfun I get the same errors
catFunc = @(aa, bb) strjoin(cell(aa,bb), '_')
catFunc(T.b(1), T.c(1))
What am I doing wrong here? I'm confused why the first version of the function doesn't work and strjoin isn't seeing a cell array of strings, and I'm confused why changing the {} in the function call to cell() changes the error I'm seeing
댓글 수: 1
답변 (2개)
Cris LaPierre
2018년 12월 9일
Not super familiar with rowfun, so here's a simple way to get around it:
T.b = string(T.b);
T.c = string(T.c);
T.b + " " + T.c
ans =
"one uno"
"two dos"
"three tres"
per isakson
2018년 12월 9일
편집: per isakson
2018년 12월 9일
Replace
rowfun(@(aa, bb) {strjoin({aa,bb}, '_')}, T, 'InputVariables', {'b', 'c'})
by
rowfun( @(aa,bb) {strjoin([aa,bb],'_')}, T, 'InputVariables', {'b','c'})
since aa and bb already are cell arrays. Then you get
ans =
3×1 table
Var1
____________
'one_uno'
'two_dos'
'three_tres'
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!