textscan syntax help converting file
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Steven Lord
2023-12-7
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.
采纳的回答
Star Strider
2023-12-7
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 个评论
Star Strider
2023-12-12
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'})]
.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!