필터 지우기
필터 지우기

Storage elements from matrix in other one, with indexing.

조회 수: 2 (최근 30일)
Isai Fernandez
Isai Fernandez 2021년 5월 10일
댓글: KSSV 2021년 5월 10일
I want to storage information from one matrix to another. In this example, from A matrix I have to extract to storage in B matrix. The solution should be:
B = [6 4
6 8]
I tried so hard, I don't get it.
Please help me.
A = [
8 3 0 2
9 6 1 4
10 6 2 1
1 6 2 8
];
a=2;
b=4;
B = zeros(2)
m=1
while m<=2
k= 1
while k<=2
i=1
while i<=4
if i==a
n1 = i
if n1<=2
j = 1
while j<=4
if j==b
n2=j
if n2<=2
B(m,k) = B(m,k)+A(n1,n2)
%B(m,k) = B(m,k)+A(n1,n2)
end
end
j = j+1
end
end
end
i = i+1
end
k = k+1
end
m=m+1
end
  댓글 수: 2
KSSV
KSSV 2021년 5월 10일
What output you expect?
Isai Fernandez
Isai Fernandez 2021년 5월 10일
B matrix with elements from A with index a and b.

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

채택된 답변

KSSV
KSSV 2021년 5월 10일
A = [8 3 0 2
9 6 1 4
10 6 2 1
1 6 2 8
];
a=2;
b=4;
[X,Y] = meshgrid([a b],[a b]) ;
id = sub2ind(size(A),Y,X) ;
B = A(id) ;
B
B = 2×2
6 4 6 8
  댓글 수: 3
KSSV
KSSV 2021년 5월 10일
A = [8 3 0 2
9 6 1 4
10 6 2 1
1 6 2 8
];
a=2;
b=4;
[X,Y] = meshgrid([a b],[a b]) ;
[m,n] = size(X) ;
B = zeros(m,n) ;
for i = 1:m
for j = 1:n
B(i,j) = A(Y(i,j),X(i,j)) ;
end
end
Loop will be slower....the solution shown first will be fast.
KSSV
KSSV 2021년 5월 10일
The answer is good.... You use that answer.

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

추가 답변 (1개)

Stephen23
Stephen23 2021년 5월 10일
The MATLAB approach:
A = [8,3,0,2;9,6,1,4;10,6,2,1;1,6,2,8]
A = 4×4
8 3 0 2 9 6 1 4 10 6 2 1 1 6 2 8
v = [2,4];
out = A(v,v)
out = 2×2
6 4 6 8
  댓글 수: 2
Isai Fernandez
Isai Fernandez 2021년 5월 10일
Wow, I have to figure out to implement this short code.
KSSV
KSSV 2021년 5월 10일
I missed the common sense....

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

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by