How to create a loop to add matrix columns?

11 views (last 30 days)
Rijul Chauhan
Rijul Chauhan on 2 Apr 2022
Edited: Stephen23 on 5 Apr 2022
Hello all,
I am pretty new to matlab and I am trying to sum the columns of multiple matrices. The matrices have names OP0A0.......OP0A24.
Currently, I have it hardcoded. How can I use the for loop to automate this?
S0 = sum(OP0A0,2);
.
.
.
S24 = sum(OP0A24,2);
Thank you!
  2 Comments
Rijul Chauhan
Rijul Chauhan on 2 Apr 2022
I used this bit of code to get all the data files imported as matries:
files = dir('*.txt');
for i=1:length(files)
load(files(i).name, '-ascii');
end

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 5 Apr 2022
Edited: Stephen23 on 5 Apr 2022
The best approach is to avoid the need to write such bad code. The most important steps are:
  • use a more suitable importing function, e.g. READMATRIX, rather than relying on an outdated syntax of the venerable LOAD, which should only be used for LOADing .mat files.
  • use basic indexing to store the imported data in a variable (e.g. the structure returned by DIR).
Doing so easily avoids the badly-designed data and code that you are forced to write. For example:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.txt'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
M = readmatrix(F);
S(k).data = M;
S(k).sum2 = sum(M,2);
end
You can trivially use indexing to access the matrices and the sums, e.g. for the second file:
S(2).name % the filename
S(2).data % the raw matrix
S(2).sum2 % the summed data
Better, simpler, much more efficient code, with no ugly EVALIN or EVAL anywhere.

Santosh Fatale
Santosh Fatale on 5 Apr 2022
Hi Rijul,
I understand that you want to calculate column sum of multiple matrices which carries similar names. I assume that the result of each of the operation need to be stored in separate variable which also carries similar names, different than the input matrix, with different subscript. You want to implement this repeated operation on each of the matrix using a loop. Please find the sample code to implement desired operations using loop.
for ii = 0 : 10
str1 = strcat('OP0A',num2str(ii)) % OP0A variable common variable name
str2 = strcat('S',num2str(ii),'=sum(',str1,',2)') % creates expression for evaluation
evalin('base','str2')
end
For more info, refer to the documentation of strcat, num2str, and evalin functions.
  1 Comment
Stephen23
Stephen23 on 5 Apr 2022
Edited: Stephen23 on 5 Apr 2022
Ugh.
Or you could learn how to avoid the need to write slow, complex, inefficient, obfuscated code like this.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!