How to create a loop to add matrix columns?

조회 수: 11 (최근 30일)
Rijul Chauhan
Rijul Chauhan 2022년 4월 2일
편집: Stephen23 2022년 4월 5일
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
Stephen23
Stephen23 2022년 4월 2일
You did not tell us the most important information: how did you get all of those matrices into the workspace?
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.
  댓글 수: 1
Stephen23
Stephen23 2022년 4월 5일
편집: Stephen23 2022년 4월 5일
Ugh.
Or you could learn how to avoid the need to write slow, complex, inefficient, obfuscated code like this.

댓글을 달려면 로그인하십시오.

카테고리

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