How to include specific rows and columns of matrices into a zero matrix
8 ビュー (過去 30 日間)
古いコメントを表示
Hi everyone,
I have a vector V (1x8) that include the number ID of some columns of a zero matrix A=[2x30000].
For the specific columns included in the vector V, I have a matrix M (2x8) that includes the values corresponding to that specific column.
Since I need this for an iterative process, is there a way to use the vector V to identify the corresponding column of the A, and then use it as a reference to insert at those specific columns the numbers of M?
Thank you in advance.
As an example:
A=zeros(2,8);
V=[1 4 7];
M=[1 2 3; 4 5 6];
ResultingA= [1 0 0 2 0 0 3 0;4 0 0 5 0 0 6 0];
0 件のコメント
採用された回答
Dirk Engel
2023 年 7 月 12 日
A(:, V) = M
inserts M into A at columns V.
This works if M and A have the same number of rows, and if M has as many columns as there are indices in V. Otherwise, you wil get some kind of indexing error.
その他の回答 (1 件)
Malay Agarwal
2023 年 7 月 12 日
You can do this as shown:
A=zeros(2,8);
V=[1 4 7];
M=[1 2 3 4 5 6 7 8; 9 10 11 12 13 14 15 16];
A(:, V) = M(:, V);
A
3 件のコメント
Stephen23
2023 年 7 月 12 日
編集済み: Stephen23
2023 年 7 月 12 日
"I'm attaching my variables, as I cannot make it work. It gives out this error: Index in position 2 exceeds array bounds. Index must not exceed 176."
The code given in this answer is buggy. The correct approach does not index into the RHS, as Dirk Engel showed here:
Using your data:
S = load('variables.mat')
A = zeros(2,30000);
A(:,S.nN) = S.N
You might like to consider doing the introductory tutorials, which show how to do indexing operations:
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!