Cellfun on cellarray from textread not working
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Guillaume
il 20 Set 2014
Modificato: Guillaume
il 20 Set 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!