How to create cell array with a function?
조회 수: 3 (최근 30일)
이전 댓글 표시
I need to create a function that takes each line from a text file and stocks this line in a cell array. The text file goes as so:
A B C D E
E D C B A
A D C B E
and so on. (the number of lines is unknown) I need it to stock as so:
{'A','B','C','D','E'}
{'E','D','C','B','A'}
and so on. My code is:
function [ T ] = ReadFile( File ) %imposed as format of the function
fid=fopen(File,'rt');
if fid~=-1
disp('File open.')
str=0;
i=1;
while ischar(str)
str=fgetl(fid);
T(i).items=strsplit(str) %here is how I stock the lines in a cell array, the field has to be named items.
i=i+1;
end
else
error('File not opened correctly')
end
However, I cannot seem to see the cell array in my main file, when I call the function. What am I doing wrong? Thank you
댓글 수: 0
답변 (1개)
Stephen23
2017년 4월 7일
편집: Stephen23
2017년 4월 8일
A more efficient concept would use something like textscan:
function C = myfun(file)
opt = {'CollectOutput',true};
fmt = repmat('%s',1,5);
[fid,msg] = fopen(file);
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
C = num2cell(C{1},2); % nested cell array for each row
# C = C{1}; % one cell array with all values
end
and then simply call it like this:
C = myfun('myfilename')
댓글 수: 4
Stephen23
2017년 4월 9일
편집: Stephen23
2017년 4월 9일
Your code works for me:
>> T = ReadFile('answers.txt')
File open.
T =
1x6 struct array with fields:
items
May be you have multiple versions of your function saved, and an older version is getting called (and not the version that you think/want). Tell us what the output of this command is:
which ReadFile -all
Is this the location which you expect? Are multiple files listed? Is the directory where you have your function saved on the MATLAB search path?
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!