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];

채택된 답변

Dirk Engel
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
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
A = 2×8
1 0 0 4 0 0 7 0 9 0 0 12 0 0 15 0
  댓글 수: 3
Stephen23
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')
S = struct with fields:
N: [2×176 double] nN: [1 8791 2 3 8042 4 5 7683 306 9234 305 8732 304 7851 303 9236 302 7266 301 7272 300 7774 299 7807 298 7219 297 7843 296 9079 295 9044 294 9239 293 9347 292 9382 291 9834 290 8817 289 … ]
A = zeros(2,30000);
A(:,S.nN) = S.N
A = 2×30000
-0.0210 -0.0200 0.0200 0.0210 0.0210 -0.0210 -0.0200 0.0200 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0100 0.0100 0.0100 0.0100 -0.0100 -0.0100 -0.0100 -0.0100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
You might like to consider doing the introductory tutorials, which show how to do indexing operations:
Stefano Russo
Stefano Russo 2023년 7월 12일
I have to indeed. Thank you everyone for your help. I'll try my best not to fill this community with silly questions. :)

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by