How to create a loop to add matrix columns?
11 次查看(过去 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 个评论
Stephen23
2022-4-2
You did not tell us the most important information: how did you get all of those matrices into the workspace?
回答(2 个)
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.
0 个评论
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!