extracting first letter from the cell
38 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
KDRA
el 15 de Oct. de 2018
Editada: Kyle Pastor
el 9 de Abr. de 2020
hello,
I have two cell arrays: nam1 = {'John', 'Adam', 'Emma'} nam2 = {'Doe', 'Willson', 'Brown'}
I want to create one array with initials, like this: init = {'JD', 'AW', EB'}
I tried extracting first letters from each array like this:
if true
% code
end
ininam1 = cellfun (@(x) x(1),nam1,'un',0)
ininam2 = cellfun (@(x) x(1),nam2,'un',0)
but this already fails (Index exceeds array bounds). Can you help me with this? Also combining these two arrays together?
Thanks in advance!
K.
2 comentarios
Stephen23
el 15 de Oct. de 2018
It worked fine when I tried it:
>> nam1 = {'John', 'Adam', 'Emma'};
>> nam2 = {'Doe', 'Willson', 'Brown'};
>> ininam1 = cellfun (@(x) x(1),nam1,'un',0)
ininam1 = 'J' 'A' 'E'
>> ininam2 = cellfun (@(x) x(1),nam2,'un',0)
ininam2 = 'D' 'W' 'B'
Kyle Pastor
el 9 de Abr. de 2020
Editada: Kyle Pastor
el 9 de Abr. de 2020
I had the same issue. Turns out one of the elements of my cell arrays was an empty string.
A = {'Works','OK_DOKIE',''};
element 3 will cause the fail!
-K
Respuesta aceptada
Kevin Chng
el 15 de Oct. de 2018
Editada: Kevin Chng
el 15 de Oct. de 2018
Hi,
nam1 = {'John', 'Adam', 'Emma'} ; nam2 = {'Doe', 'Willson', 'Brown'};
ininam1 = strcat(nam1{1}(1),nam2{1}(1))
3 comentarios
Kevin Chng
el 15 de Oct. de 2018
It will return all the combination in name
nam1 = {'John', 'Adam', 'Emma'} ;
nam2 = {'Doe', 'Willson', 'Brown'};
ininam1 = cellfun (@(x) x(1),nam1,'un',0);
ininam2 = cellfun (@(x) x(1),nam2,'un',0);
name=strcat(ininam1,ininam2);
Más respuestas (1)
Adam
el 15 de Oct. de 2018
res = cellfun( @(x,y) [x(1) y(1)], nam1, nam2, 'UniformOutput', false' )
works fine for me on your example, but then so does your own code. Do you have an actual example where it leads to an error?
3 comentarios
Adam
el 15 de Oct. de 2018
Editada: Adam
el 15 de Oct. de 2018
Well, the problem certainly appears to be with your inputs, but I don't know from that exactly what the inputs look like. The example you gave works fine and I would imagine any pair of cell arrays of equal length, each of which have names of at least 1 letter in them would work. If you have empty cells or if nam1 and nam2 are not the same length then it won't work.
What do nam1 and nam2 look like in a real case that fails? Giving a simplified example in a question is useful, but only if it replicates the problem you are having for the question you ask!
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!