textscan syntax help converting file
2 views (last 30 days)
Show older comments
I'm trying to read in a .txt file and convert the contents to an array. The text file is always formatted as follows (with additional items always on new lines):
Array = {
'Item1', 2526976, 8, 14, 11, [224,224,137,80];
'Item2', 2526976, 8, 18, 15, [224,224,137,80];
};
What is the sytax I use to use with textscan so that it loads into the workspace as follows:
1 Comment
Steven Lord
on 7 Dec 2023
If the file is formatted using MATLAB syntax, rather than trying to read it as data I'd consider renaming it to have the extension .m instead of the extension .txt. If you do that you could run it as a MATLAB script file.
Accepted Answer
Star Strider
on 7 Dec 2023
Try something like this —
Array = {'Item1', 2526976, 8, 14, 11, [224,224,137,80]
'Item2', 2526976, 8, 18, 15, [224,224,137,80]};
fido = fopen('Test.txt','wt')
for k = 1:size(Array,1)
fprintf(fido, '%s, %d, %d, %d, %d, [%d,%d,%d,%d]\n',Array{k,:});
end
fclose(fido);
type('Test.txt')
fidi = fopen('Test.txt','rt');
C = textscan(fidi, '%s %d %d %d %d [%d %d %d %d]', 'Delimiter',{','}, 'CollectOutput',1)
fclose(fidi);
C
C{1}
C{2}
.
2 Comments
Star Strider
on 12 Dec 2023
This is as close as I can get to that —
Array = {'Item1', 2526976, 8, 14, 11, [224,224,137,80]
'Item2', 2526976, 8, 18, 15, [224,224,137,80]};
fido = fopen('Test.txt','wt');
for k = 1:size(Array,1)
fprintf(fido, '%s, %d, %d, %d, %d, [%d,%d,%d,%d]\n',Array{k,:});
end
fclose(fido);
type('Test.txt')
fidi = fopen('Test.txt','rt');
C = textscan(fidi, '%s %d %d %d %d [%d %d %d %d]', 'Delimiter',{','}, 'CollectOutput',1)
fclose(fidi);
C
C{1}
C{2}
T1 = array2table(cell2mat({C{2}(:,1:4)}));
T1 = [addvars(T1,C{1}, 'Before',1) table(cell2mat({C{2}(:,5:8)}),'VariableNames',{'Var5'})]
.
More Answers (0)
See Also
Categories
Find more on Text Files 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!