필터 지우기
필터 지우기

How to extract value from a matrix with given indices

조회 수: 23 (최근 30일)
Shin
Shin 2023년 1월 17일
댓글: Shin 2023년 1월 17일
Hi there,I have a an array of index and a matrix such as
index = [2 4 3 1 5];
matrix = [5 2 5 3 4;
1 2 4 2 6;
7 5 0 9 3;
6 6 3 1 2;
3 6 8 2 7];
How can I extract the value from each column of the matrix with the given index to obtain a new array such as
new = [1 6 0 3 7];
Thanks.
-Shin-

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 1월 17일
index = [2 4 3 1 5];
matrix = [5 2 5 3 4;
1 2 4 2 6;
7 5 0 9 3;
6 6 3 1 2;
3 6 8 2 7];
s=size(matrix);
new=matrix(sub2ind(s,index,1:s(2)))
new = 1×5
1 6 0 3 7
  댓글 수: 1
Shin
Shin 2023년 1월 17일
Hi Dyuman Joshi, thanks for solution, it works well too, more simplify way.

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

추가 답변 (2개)

Abhinav
Abhinav 2023년 1월 17일
편집: Abhinav 2023년 1월 17일
index = [2 4 3 1 5];
matrix = [5 2 5 3 4;
1 2 4 2 6;
7 5 0 9 3;
6 6 3 1 2;
3 6 8 2 7];
new=[];
for i=1:length(index)
new(i)=matrix(index(i),i);
end
new
  댓글 수: 1
Shin
Shin 2023년 1월 17일
Hi Abhinav, thank for the solution, however the code only display the last value with is "new = 7" in this case. After I modify a little on your code and I'm able to get all the value. Code as below.
index = [2 4 3 1 5];
matrix = [5 2 5 3 4;
1 2 4 2 6;
7 5 0 9 3;
6 6 3 1 2;
3 6 8 2 7];
indexNO = 5;
new = zeros(1,indexNO);
for i = 1:indexNO
new(1,i) = matrix(index(i),i);
end
new
Anyway, thanks again for you solution.

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


prasanth s
prasanth s 2023년 1월 17일
code example is
ind = sub2ind(size(matrix),index,1:5);
new=matrix(ind)
  댓글 수: 1
Shin
Shin 2023년 1월 17일
Hi Prasanth, thanks for your solution too, works as well, appreciate it.

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

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by