Removing Columns and Rows of a Matrix When Future Deletions Reference the Original Matrix
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
So I am deleting rows and columns based on the find function's row and column outputs. When I use the row and column arrays to delete from the matrix, the dimensions of the matrix change and renders the initial find function output's incorrect. Any suggestions to get around this?
Replacing [] with [0] preserves the original matrix's dimensions but now I am not sure how to get rid of the zeros.
*These aren't the K matrixes that I use in the actual code - these were made for debugging.
K1 = [12 12 12 12; 12 12 12 12; 12 12 12 12; 12 12 12 12];
K2 = ones(4,4);
K3 = [2 2 2 2; 2 2 2 2; 2 2 2 2; 2 2 2 2];
q1 = [7; 8; 1; 2];
q2 = [1; 2; 5; 6];
q3 = [5; 6; 3; 4];
[K] = assembleGlobalStiffnessMatrix(numconst, dofzero, K1, K2, K3, q1, q2, q3)
function [K] = assembleGlobalStiffnessMatrix(numconst, dofzero, x, y, z, qq, qw, qe)
q = [qq; qw; qe]; %global dof
b = zeros(4,4);
K = [x b b; b y b; b b z]; %global K
%cutting down
for n = 1:numconst
[row, col] = find(dofzero == q)
end
for d = 1:size(row)
K(row,:) = []; % row removal
K(:, col) = []; % column removal
end
end
1 Commento
Deepak Gupta
il 28 Ott 2021
Provide a working code. Here numconst, dofzero variables are unknown so cant reproduce the error you are seeing.
Risposte (1)
Gyan Vaibhav
il 13 Ott 2023
Hi Marissa,
The issue you are experiencing is a common one when deleting elements from a matrix in a loop. The size of the matrix changes with each iteration, which can lead to indexing errors or incorrect results.
A better approach would be to collect all the rows and columns you want to delete first, and then delete them all at once. This way, the size of the matrix does not change while you are determining which elements to delete.
Here is how you can do it:
function [K] = assembleGlobalStiffnessMatrix(numconst, dofzero, x, y, z, qq, qw, qe)
q = [qq; qw; qe]; %global dof
b = zeros(4,4);
K = [x b b; b y b; b b z]; %global K
%cutting down
rows_to_delete = [];
cols_to_delete = [];
for n = 1:numconst
[row, col] = find(dofzero == q)
rows_to_delete = [rows_to_delete; row];
cols_to_delete = [cols_to_delete; col];
end
K(rows_to_delete,:) = []; % row removal
K(:, cols_to_delete) = []; % column removal
end
This code first finds all the rows and columns to delete and stores them in “rows_to_delete” and “cols_to_delete”. Then it removes all these rows and columns from “K” at once. This way, the size of “K” does not change while you are finding the elements to delete.
Hope this helps.
0 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!