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!