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

2 ビュー (過去 30 日間)
Marissa Strandmo
Marissa Strandmo 2021 年 10 月 28 日
回答済み: Gyan Vaibhav 2023 年 10 月 13 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by