joining string variables in a table with strjoin and rowfun
20 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Réponses (2)
Cris LaPierre
le 9 Déc 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"
1 commentaire
per isakson
le 9 Déc 2018
Modifié(e) : per isakson
le 9 Déc 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 commentaires
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!