How to create cell array with a function?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Stephen23
am 7 Apr. 2017
Bearbeitet: Stephen23
am 8 Apr. 2017
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 Kommentare
Stephen23
am 9 Apr. 2017
Bearbeitet: Stephen23
am 9 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?
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!