How do I perform a loop on one matrix after the next?
2 views (last 30 days)
Show older comments
A = [1 4 0 1 1; -1 -5 9 -20 2; 15 1 4 5 1; 2 2 -5 0 0; 0 2 -3 1 -9];
B = [9 3 3; 12 3 2; 1 3 5];
C = [1 13 2; 1 3 9; -12 2 -1];
D = [5 -2 4 2; 0 3 -1 -1; 3 3 9 -5; 1 1 1 5];
[maxrow, ind] = max(abs(A), [], 2);
if all(2 * maxrow > sum(abs(A), 2)) && isequal(sort(ind),(1:numel(ind)))
A(ind, :) = M_A
disp('This matrix can be made diagonally dominant');
M_A
else
disp('This matrix can NOT be made diagonally dominant')
M_A = A;
M_A
end
Apologies is the question is worded badly.
So the code above checks if matrix A can be made diagonally dominant through row swaps, then the resultant matrix (in its diagonally dominant form, or in its initial form if it cannot be transformed into a diagonally dominant matrix) is stored as a new variable M_A (where the 2nd letter is the matrix being analysed - A in this case) .
However I want to carry out the analysis on all the matirces A - D either at once or one by one.
I cant think of a way to do this except copy and paste the code another 3 times and changing the matrix its analysing.
Any suggestions??
0 Comments
Accepted Answer
Ameer Hamza
on 21 Apr 2020
Edited: Ameer Hamza
on 21 Apr 2020
Due to such issues, it is always recommended to create arrays for related data instead of creating several variables. In this case, creating a cell array will simplify the code
A = [1 4 0 1 1; -1 -5 9 -20 2; 15 1 4 5 1; 2 2 -5 0 0; 0 2 -3 1 -9];
B = [9 3 3; 12 3 2; 1 3 5];
C = [1 13 2; 1 3 9; -12 2 -1];
D = [5 -2 4 2; 0 3 -1 -1; 3 3 9 -5; 1 1 1 5];
M = {A,B,C,D};
M_A = cell(1,numel(M));
for i=1:numel(M)
[maxrow, ind] = max(abs(M{i}), [], 2);
if all(2 * maxrow > sum(abs(M{i}), 2)) && isequal(sort(ind),(1:numel(ind)))
M{i}(ind, :) = M_A{i};
disp('This matrix can be made diagonally dominant');
M_A{i}
else
disp('This matrix can NOT be made diagonally dominant')
M_A{i} = M{i};
M_A{i}
end
end
3 Comments
Stephen23
on 21 Apr 2020
"Any ideas will be helpful!"
Your code would be simpler, more generalized, and more efficient if you changed your approach a little bit: instead of having separate matrices with different names, you should just use one cell array (as Ameer Hamza has shown you) together with very efficient indexing. Then your code would trivially expand to any number of matrices, and you could trivially access any of them using basic indexing:
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!