Cellfun on cellarray from textread not working
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
Guillaume
2014년 9월 20일
편집: Guillaume
2014년 9월 20일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!