필터 지우기
필터 지우기

assign values to a matrix without a loop

조회 수: 3 (최근 30일)
Victor Hugo Cantú
Victor Hugo Cantú 2019년 2월 26일
댓글: KSSV 2019년 2월 27일
I want to access to some elements of a matrix.
I have a matrix P :
P = [1 2 3 4 5 6 7 8
2 1 3 4 5 6 7 8
3 4 2 1 5 6 7 8
4 3 5 2 6 1 7 8
5 4 6 3 7 2 8 1
6 5 7 4 8 3 9 2
7 8 6 9 5 10 4 11
8 7 9 10 6 11 5 12
9 10 8 11 7 12 6 13
10 9 11 8 12 7 13 6];
and a matrix A :
A = [5 4
2 8
1 5
4 3
2 6
2 3
1 3
4 6
4 6
5 8];
I want to obtain the A element of P in S, for example
S(1,:) = [5 4]
S(2,:) = [1 8]
S(3,:) = [3 5]
...
S(9,:) = [11 12]
S(10,:) = [12 6]
I konw how to do it with a for loop, but, is there a way to do it without any loop ?
  댓글 수: 2
madhan ravi
madhan ravi 2019년 2월 27일
not clear
Victor Hugo Cantú
Victor Hugo Cantú 2019년 2월 27일
편집: Victor Hugo Cantú 2019년 2월 27일
for being clear, I put the way to do it using a for loop
for i = 1:size(A,1)
S(i,:) = P(i,A(i,:));
end
How can I do the same without the for loop ?

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

채택된 답변

KSSV
KSSV 2019년 2월 27일
편집: KSSV 2019년 2월 27일
[m,n] = size(P) ;
I = repmat((1:m)',1,2) ;
idx = sub2ind(size(P),I,A) ;
iwant = P(idx)
  댓글 수: 2
Victor Hugo Cantú
Victor Hugo Cantú 2019년 2월 27일
thank you very much ! it works ! in my exampe m = 10.
KSSV
KSSV 2019년 2월 27일
Oh.....yes..m = 10. Edited the code.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by