how to combine text files using load function?

8 views (last 30 days)
i want to combine A,B,C files into one file.
But i faced error , Error using horzcat Dimensions of arrays being concatenated are not consistent.
this is my code
%put files to combine
File = {file_name_1, file_name_2,file_name_3};
A = [];
for index = 1 : numOfFile
newA = load(File{index});
A = [A newA];
% save final output
save('outputFile.txt', 'A')
Kevin Chng
Kevin Chng on 4 Oct 2018
Walter's Roberson mentioned that it might have error due to different number of columns.
Do you mind provide few of your files for me to try out?

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 5 Oct 2018
The below code assumes the files are to be put side by side, and assumes that the number of rows in the files might be different. The number of columns in each file does not need to be the same at all. Shorter rows are padded with the value of your choice.
pad_value = nan; %change to 0 if you want padding by 0
%put files to combine
File = {file_name_1, file_name_2,file_name_3};
for index = 1 : numOfFile
newA = load(File{index});
if ndims(newA) > 2
error('File "%s" has more than 2 dimensions', File{index});
if index == 1
A = newA;
[or, oc] = size(A);
[nr, nc] = size(newA);
if nr > or %new file has more rows than any previous file
A(or+1:nr, :) = pad_value;
or = nr;
if nr < or %new file has fewer rows than some previous file
newA(nr+1:or, :) = pad_value;
nr = or;
A(:, end+1:end+nc) = newA;
% save final output
save('outputFile.txt', 'A', '-ascii', '-double')
The logic would be much the same for the case of putting the files under each other but not assuming that the number of columns are the same.

Raghunandan V
Raghunandan V on 5 Oct 2018
Since you are trying to do in arrays you are not able to concancate You should try it using cell arrays. something like this
fileName={'new1.txt', 'new2.txt', 'new3.txt'};
%open file identifier
for k=1:length(fileName)
%read the file name as string including delimiters and next lines
%arrange them in order of k if you want in a cell array
%or print them into a file.
fprintf(fid, [cell2mat(List) '\n']);
%close file indentifier


Find more on Resizing and Reshaping Matrices 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!