Cellfun on cellarray from textread not working

3 views (last 30 days)
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!

Accepted Answer

Guillaume
Guillaume on 20 Sep 2014
Edited: Guillaume on 20 Sep 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 Comment
Stefan
Stefan on 20 Sep 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

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays 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!