How can I insert many columns into a matrix at different locations efficiently?

2 ビュー (過去 30 日間)
Darcy Cordell
Darcy Cordell 2022 年 9 月 26 日
コメント済み: Chunru 2022 年 9 月 28 日
I have a matrix in which I need to delete several columns of zeros, perform some operation (i.e. matrix inverse), and then re-insert the zero columns back into the matrix at the same position. My matrix is very large, so I don't want to store a duplicate of the matrix in memory. For example:
%Create some "data"
A = rand(100); %some random data
A(:,randsample(100,15))=zeros(100,15); %some random columns of zeros
%Now that we have "data", let's find the zero columns:
col = find(~all(A));
%Delete the zero columns
A(:,col) = [];
%Now do some stuff to A ....
%Now I want to re-add the columns in????
One simple option to solve the problem is:
for i = 1:length(col)
A = [A(:,1:col(i)-1) zeros(100,1) A(:,col(i):end)];
end
But I feel like there must be a more elegant way to do it without the for loop that can essentially "reverse" the deletion. Any help is appreciated.
  3 件のコメント
James Tursa
James Tursa 2022 年 9 月 27 日
Can you give us details about what operations you are performing on the non-zero columns of A?
Darcy Cordell
Darcy Cordell 2022 年 9 月 27 日
I need to invert the non-zero columns. I've updated the answer accordingly.

サインインしてコメントする。

回答 (1 件)

Chunru
Chunru 2022 年 9 月 27 日
編集済み: Chunru 2022 年 9 月 27 日
%Create some "data"
A = rand(100); %some random data
col = randsample(100,15);
A(:, col)=zeros(100,15); %some random columns of zeros
%Now that we have "data", let's find the zero columns:
col = find(all(A==0))
col = 1×15
1 2 4 5 7 20 33 35 41 49 67 69 70 86 92
% No need to delete the zero columns
% Just re-assign anything back to A
%
% This is a faster approach since array size is kept the same.
%
% For example
A(:, col) = ones(size(A,1), length(col));
  2 件のコメント
Darcy Cordell
Darcy Cordell 2022 年 9 月 27 日
The problem is that I need to perform some operations on the non-zero columns of A (i.e. matrix inverse). So I can't replace the columns with ones, I need to delete the columns prior to taking the inverse.
Chunru
Chunru 2022 年 9 月 28 日
You can refenrence to the sub array. But we dont know what you exactly want to do.

サインインしてコメントする。

カテゴリ

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