joining string variables in a table with strjoin and rowfun

56 次查看(过去 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 个评论
Stephen23
Stephen23 2023-3-8
编辑:Stephen23 2023-3-8
Using ROWFUN is like cracking a walnut with a sledgehammer. Simpler (even before the string class):
a = [1;2;3];
b = {'one'; 'two'; 'three'};
c = {'uno'; 'dos'; 'tres'};
T = table(a,b,c)
T = 3×3 table
a b c _ _________ ________ 1 {'one' } {'uno' } 2 {'two' } {'dos' } 3 {'three'} {'tres'}
strcat(T.b,'_',T.c)
ans = 3×1 cell array
{'one_uno' } {'two_dos' } {'three_tres'}

请先登录,再进行评论。

回答(2 个)

Cris LaPierre
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
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'

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by