I have three matrices A B C containing numerical data and which are of unequal lengths (e.g. A=88x1, B=121x1, C=240x1 - lengths are variable between data sets). In order to print these to a .txt file without padarray and to fill in the unequal lengths with white space instead, i've been using:
con = [{A} {B} {C}];
lens = cellfun('length',con);
max_length = max(lens);
con_reg = cell(max_length,numel(lens));
con_reg(:) = {''};
con_reg(bsxfun(@le,[1:max_length]',lens)) = cellstr(num2str(vertcat(con{:})));
wspace = repmat({char(9)},max_length,1);
out_str = [];
for iter = 1:numel(con)
out_str = [out_str char(con_reg(:,iter)) char(wspace)];
end
out_cell = cellstr(out_str);
ext = '.txt';
filename = strcat((genotype{1}),'-',num2str(threshold),'bpThresh',ext);
fid1 = fopen(filename{1},'wt');
for row = 1:numel(out_cell)
fprintf(fid1,'%s\n',out_cell{row});
end
fclose(fid1);
toc
However this feels quite convoluted and difficult to read.
Is there a more concise, simpler way to accomplish this?
Secondly, one feature I particularly like about writetable is the ability to include column headers. How could I incorporate this into a solution? writetable itself seems to explicitly require vectors of equal length and thus padding. I'm working on OS X so using xlswrite is not much of a viable option.
EDIT:
I've reduced down the necessary code by making use of tables and writetable:
con = [{A} {B} {C}];
lens = cellfun('length',con);
max_length = max(lens);
con_reg = cell(max_length,numel(lens));
con_reg(:) = {''};
con_reg(bsxfun(@le,[1:max_length]',lens)) = cellstr(num2str(vertcat(con{:})));
T = cell2table(con_reg);
ext = '.txt';
filename = strcat((genotype{1}),'-',num2str(threshold),'bpThresh',ext);
writetable(T,filename{1},'Delimiter','\t');
Interested if there are any more improvements that can be made.
csvwritewrite multiple matrices? It appears to only be able to write a single, combined matrix. - AnnaSchumanncsvwriteworks only with one matrix but there are other ways to create csv files. Check my answer below. (Ps: I can't mention your name in the comment don't know why) - Lati