Matrix addition from multiple files

1 view (last 30 days)
Gollapalli Prince
Gollapalli Prince on 11 Apr 2019
Commented: Jon on 22 Apr 2019
I have 240 matrices stored in 240 files with the name DOS1.dat DOS2.dat ......DOS240.dat.
The matrix size is 300x19. How to do a matrix addition.

Accepted Answer

Jon
Jon on 11 Apr 2019
You haven't provided enough detail to answer your question too specifically but in general the steps would be to read the individual data files into MATLAB and assign the data in each file to a matlab array. You could then perform the desired matrix addition on the elements of this matlab array. So for example:
% assign your dimensions
numRows = 300 % number of rows in your individual matrices
numCols = 19 % number of columns in your individual matrices
numMats = 240 % number of individual matrices
% preallocate array to hold the data
A = zeros(numRows,numCols,numMats);
% loop to read individual matrices from files
for k = 1:numMats
% build the name of the data file as a character vector'
filename = ['DOS',num2str(k)];
A(:,:,k) = readmatrix(filename);
end
% now for example add the first and third matrix
B = A(:,:,1) + A(:,:,3)
You may have to modify the above code to fit the specifics of your situation, but this should give you an idea of how it could be done.
  7 Comments
Jon
Jon on 22 Apr 2019
Hi Gollapalli,
I'm glad you finally got it working. I have only used the "load" command for loading .mat files, but I see now now from the documentation that it can also be used for loading "ascii" text files, which I guess is what you must have had. That's good to know.
Regarding your final loop to add the elements, in general it is good to take advantage of MATLAB's ability to efficiently handle such operations without loops. So you could replace the loop with
B = sum(A,3) % sum across the third dimension of A
Avoiding loops should make the code run faster, and also makes the code simpler to read.
Also, although MATLAB doesn't complain when you use a variable name that is the same as a MATLAB function, it can make things a little confusing. So in your case, your local variable named "sum" is actually taking the place of the MATLAB sum command. If later in your code you tried to use the "sum" command it would not work, as it would think that you were referring to your variable named "sum".
Jon
Jon on 22 Apr 2019
I noticed that you unaccepted the answer to this. I'm curious, which one did you find that was better? If there is a better answer, it would be good to make a comment pointing others toward it, in case they are following this thread, and it just seems to be left unanswered.

Sign in to comment.

More Answers (0)

Categories

Find more on Function Creation 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!