How can I rename all columns in a table using a cell array?
4 views (last 30 days)
Show older comments
I am trying to rename columns in a table. There are 11904 columns, so I am using a cell array for the variable names. However, I get the error:
The VariableNames property must be a cell array, with each element containing one nonempty string.
I do not know how to convert the cell array into something that can be used in the NewTable.Properties.VariableNames function. Thanks!
Here is my code:
disp('Converting .txt measurements to .csv...')
dirs = dir(pathname_meas);
for i = 1:length(dir(pathname_meas));
if strfind(dirs(i).name,'All.txt');
datas = readtable(dirs(i).name,'delimiter','\t');
ncols = (height(datas)/std_erp_count);
channels=[64,32];
counter=1;
bin_num=1;
col_labs=cell(1, ncols);
for j = 1:(ncols)
if counter < channels(2-ch64)
col_labs{j}=strcat(datas(j,'chlabel').chlabel,'_',int2str((bin_num)));
counter=counter+1;
else
col_labs{j}=strcat(datas(j,'chlabel').chlabel,'_',int2str((bin_num)));
counter = 1;
bin_num=bin_num+1;
end
end
% create new matrix - participant x electrode
transposed_column = transpose(table2cell(datas(:,'value')));
newTable = reshape(transposed_column,ncols, std_erp_count);
newTable = array2table(transpose(newTable));
% Change column names
for new_column_names = 1:length(col_labs)
newTable.Properties.VariableNames(new_column_names)=col_labs{new_column_names};
end
% newTable.Properties.VariableNames=col_labs;
disp('Writing measurements to .csv file...')
writetable(newTable,[pathname_meas strcat(dirs(i).name(1:length(dirs(i).name)-3),'csv')],'Delimiter',',');
end
3 Comments
per isakson
on 30 Sep 2017
Edited: per isakson
on 30 Sep 2017
>> iscellstr(col_labs)
ans =
0
needs to show 1, i.e true. The reason was (you have now edit the code) that col_labs was a cell array of cells of a string (as @Jan writes in his answer.)
Answers (1)
Jan
on 30 Sep 2017
col_labs{i}={strcat(char(table_columns_1(i)),'_',int2str((counter)))};
creates a cell, which contains cell strings. Better:
col_labs{i} = strcat(table_columns_1{i}, '_', int2str((counter)));
Note that you have 2 nested "for i" loops:
for i = 1:length(dir(pathname_meas));
...
for i = 1:(11904)
This is at least confusing.
Try this:
col_labs = cell(1, 11904); % Pre-allocate!!!
for iFile = 1:length(dirs)
if strfind(dirs(i).name, 'All.txt');
datas = readtable(dirs(i).name, 'delimiter', '\t');
table_columns_1 = table2cell(datas(:, 'chlabel'));
counter = 1; % Inside the loop?!
for k = 1:11904
count = rem(k - 1, 64) + 1;
col_labs{k} = strcat(table_columns_1{k}), '_', int2str(counter));
end
...
See Also
Categories
Find more on Logical 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!