MATLAB表格基本操作
主要总结了一下常用的表格操作:
创建一个表格table.csv,其内容是:
%读取csv文件
T1=readtable('table.csv');
T1
%读取不含列标题的csv文件
T2=readtable('table.csv','ReadVariableNames',false);
T2
%如果数据是被空格进行分隔的
%T = readtable(filename,'Delimiter',' ','ReadVariableNames',false)
% 读取表行的名字
T3=readtable('table.csv','ReadVariableNames',false,'ReadRowNames',true);
% 表的基本操作(对于第一列其实是cell数组的操作)
T1.Var1
%注意区别以下两个的区别
T1.Var1(1)
T1.Var1{1}
%% 表的基本读取操作
%读取特定列
T1.Alice
%读取特定行(使用strcmp来选择读取哪一行)
disp('________________________________important________________________________');
find(strcmp(T1.Var1, 'two'))
%比如说读取two那一行Alice的数据,是4
T1.Alice(find(strcmp(T1.Var1,'two')))
%find(T1.Var1=='one')
%T1.Alice(find(T1.Var1=='one'))
disp('________________________________end________________________________')
%% 检测针对电子表格文件的导入选项,指定要导入的变量,然后读取数据。
% 根据文件创建导入选项对象。
opts = detectImportOptions('table.csv')
opts.SelectedVariableNames = {'Alice'};
T4=readtable('table.csv',opts);%这里就只读取了Alice的数据
T4
%% 表格的创建与保存
index=T1.Var1;
Alicemy=T1.Alice;
Bobmy=T1.Bob;
TT=table(index,Alicemy,Bobmy);
writetable(TT,'mytable.csv');
运行结果如下:
T1 =
2×4 table
Var1 Alice Bob Cindy
_______ _____ ___ _____
{'one'} 1 2 3
{'two'} 4 5 6
T2 =
2×4 table
Var1 Var2 Var3 Var4
_______ ____ ____ ____
{'one'} 1 2 3
{'two'} 4 5 6
ans =
2×1 cell 数组
{'one'}
{'two'}
ans =
1×1 cell 数组
{'one'}
ans =
'one'
ans =
1
4
________________________________important________________________________
ans =
2
ans =
4
________________________________end________________________________
opts =
DelimitedTextImportOptions - 属性:
格式 属性:
Delimiter: {','}
Whitespace: '\b\t '
LineEnding: {'\n' '\r' '\r\n'}
CommentStyle: {}
ConsecutiveDelimitersRule: 'split'
LeadingDelimitersRule: 'keep'
EmptyLineRule: 'skip'
Encoding: 'UTF-8'
替换 属性:
MissingRule: 'fill'
ImportErrorRule: 'fill'
ExtraColumnsRule: 'addvars'
变量导入 属性:
VariableNames: {'Var1', 'Alice', 'Bob' ... and 1 more}
VariableTypes: {'char', 'double', 'double' ... and 1 more}
SelectedVariableNames: {'Var1', 'Alice', 'Bob' ... and 1 more}
VariableOptions: Show all 4 VariableOptions
Access VariableOptions sub-properties using setvaropts/getvaropts
PreserveVariableNames: false
位置 属性:
DataLines: [2 Inf]
VariableNamesLine: 1
RowNamesColumn: 0
VariableUnitsLine: 0
VariableDescriptionsLine: 0
要显示该表的预览,请使用 preview
T4 =
2×1 table
Alice
_____
1
4