How to create cell array with a function?
Show older comments
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
Answers (1)
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 Comments
Dada
on 8 Apr 2017
Once I fixed some bugs (e.g. you use str but never define its value, but it probably exists in your workspace which is why the script works) your code works for me. Your description "I can't.. " does not give any information for me to understand the situation. Does "I can't.." mean that you are possessed by a strange and magical force that prevents your hand from pressing the enter button, or does "I can't.. " mean that the code throws an error (if so, please give the complete error message), or does "I can't.. " mean that the code runs but does not return the expected output (if so, please upload your data, and explain how you are calling this function), or perhaps "I can't.. " means that your computer bursts into flames when you tried. Should I call the fire brigade?
Note that testing fid~=-1 is not robust, as there are also other error codes and MATLAB already outputs an error message, so a big improvement would be:
[fid,msg] = fopen(...);
assert(fid>=3,msg)
... your code
No ugly and buggy ifs are required.
Dada
on 8 Apr 2017
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?
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!