joining string variables in a table with strjoin and rowfun
32 views (last 30 days)
Show older comments
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 Comment
Answers (2)
Cris LaPierre
on 9 Dec 2018
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
on 9 Dec 2018
Edited: per isakson
on 9 Dec 2018
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 Comments
See Also
Categories
Find more on Characters and Strings 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!