How to separate two matrices from a single matrice?

2 ビュー (過去 30 日間)
Yamina chbak
Yamina chbak 2023 年 2 月 8 日
コメント済み: Yamina chbak 2023 年 2 月 8 日
Hi, I would like to extract two matrix B and C from a matrix A to get A=B+C, where A=sparse(N,N) with N is a number.
Since index of A has two types : index = index_1 + index_2,
so the matrix B and C should be like
B= [A(i,j) , for iindex_1 and jindex;
0 otherwise]
C = [A(i,j) , for iindex_2 and jindex;
0 otherwise]
For example A= sparse(9,9):
A = [ 1 2 3
5 6 7
8 9 10];
index = {1,2,...,9}, index_1 = {2,4,6,8}, index_2={1,3,5,9}
how to write in matlab
B = sparse(9,9); C=sparse(9,9);
B = A(index_1,:) and C = A(index_2,:)
to get
B = [ 0 2 0
5 0 7
0 9 0];
C = [ 1 0 3
0 6 0
8 0 10];

採用された回答

the cyclist
the cyclist 2023 年 2 月 8 日
編集済み: the cyclist 2023 年 2 月 8 日
Here is one way:
% Inputs
A = [ 1 2 3
5 6 7
8 9 10];
index_1 = [2,4,6,8];
index_2 = [1,3,5,9];
% Get the dimensions of A
[m,n] = size(A);
% Initialize the B and C as sparse arrays that are the size of A
[B,C] = deal(sparse(m,n));
% Assign index_1 elements to B
B(index_1) = A(index_1)
B =
(2,1) 5 (1,2) 2 (3,2) 9 (2,3) 7
% Assign index_2 elements to C
C(index_2) = A(index_2)
C =
(1,1) 1 (3,1) 8 (2,2) 6 (3,3) 10
  2 件のコメント
Yamina chbak
Yamina chbak 2023 年 2 月 8 日
編集済み: Yamina chbak 2023 年 2 月 8 日
Thank you, @the cyclist, for your assistance. I completed it, however as you can see from my example, it is not working. I find that : A ~= A I + A B
Just enough for the first column!
Yamina chbak
Yamina chbak 2023 年 2 月 8 日
Now i can fix it , just edit code from @the cyclist
% Assign index_1 elements to B
B(index_1,[1:n]) = A(index_1,[1:n])
% Assign index_2 elements to C
C(index_2,[1:n]) = A(index_2,[1:n])

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by