Cellfun on cellarray from textread not working

5 visualizaciones (últimos 30 días)
Stefan
Stefan el 20 de Sept. de 2014
Comentada: Stefan el 20 de Sept. de 2014
Hey there, I have a textfile with 13 rows and one single string in every row, reading it to a cellarray with:
fileID = fopen('C:\file.txt');
C = textscan(fileID,'%s');
What I'm trying now is to get the first 4 letters all lowercase from the strings in the cells. Using
lowerC = cellfun(@lower, C, 'UniformOutput', false)
works fine. But when I try to get the first four letters (descriped here, 3rd example: http://www.mathworks.de/de/help/matlab/ref/cellfun.html) with
abbrev = cellfun(@(x) x(1:4), Clowercase, 'UniformOutput', false)
I get the output
abbrev =
{4x1 cell}
with only the first four (lowercase but full length) strings ...
When defining
C = {'AAAA1', 'BBBB2', 'CCCC3', 'DDDD4', 'EEEE5'};
It will work. Can someone explain me the difference between the manually defined cellarray and the one textscan is defining?
Thank you very much in advance!

Respuesta aceptada

Guillaume
Guillaume el 20 de Sept. de 2014
Editada: Guillaume el 20 de Sept. de 2014
This is probably because textscan returns a cell array (one cell, as you only specify one field) of cell arrays. The following should work:
fileID = fopen('C:\file.txt');
C = textscan(fileID,'%s');
lowerC = cellfun(@lower, C{1}, 'UniformOutput', false); %Note the {1}
abbrev = cellfun(@(x) x(1:4), lowerC, 'UniformOutput', false);
%or to be safe, if any element is shorter than 4 chars
abbrev = cellfun(@(x) x(1:min(end, 4)), lowerC, 'UniformOutput', false);
textscan returns a cell array where each column correspond to a field in the format string. You've only specified one field, so you get one cell. Because that field is %s that single cell is a cell array of string.
  1 comentario
Stefan
Stefan el 20 de Sept. de 2014
Thank you very much :) I already suspected the celly array was kinda different and I think I have to reread the chapter about it :D

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by