Removing Columns and Rows of a Matrix When Future Deletions Reference the Original Matrix

조회 수: 3 (최근 30일)
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
Deepak Gupta
Deepak Gupta 2021년 10월 28일
Provide a working code. Here numconst, dofzero variables are unknown so cant reproduce the error you are seeing.

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

답변 (1개)

Gyan Vaibhav
Gyan Vaibhav 2023년 10월 13일
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by