How to create a loop to add matrix columns?

20 次查看(过去 30 天)
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 个评论
Rijul Chauhan
Rijul Chauhan 2022-4-2
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

请先登录,再进行评论。

回答(2 个)

Stephen23
Stephen23 2022-4-5
编辑:Stephen23 2022-4-5
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 2022-4-5
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by