Cellfun on cellarray from textread not working
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Stefan
am 20 Sep. 2014
Kommentiert: Stefan
am 20 Sep. 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!
0 Kommentare
Akzeptierte Antwort
Guillaume
am 20 Sep. 2014
Bearbeitet: Guillaume
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!