How to create a loop to add matrix columns?
12 ビュー (過去 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!