필터 지우기
필터 지우기

matrix extract without using for loop

조회 수: 1 (최근 30일)
Sewon
Sewon 2012년 4월 2일
I have matrix like below
A=[ 1 2 3 4 5 6 7;
8 9 10 11 12 13 14;
15 16 17 18 19 20 21];
start=[1 3 4]; rowSize=2;
if I use for loop,
B=zeros(3,3);
for i=1:3
B(i,:)=A(i,start(i):start(i)+rowSize);
end
This will give
B =
1 2 3
10 11 12
18 19 20
Is ther anyway I can do the same process without using the for loop?
  댓글 수: 1
Oleg Komarov
Oleg Komarov 2012년 4월 2일
Why would you want to avoid the loop? In this case I doubt vectorization would add to the performance.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 4월 2일
start=[1 3 4];
rowSize=2;
out = cell2mat(arrayfun(@(i1)A(i1,start(i1)+(0:rowSize)),(1:size(A,1))','un',0));
OR
start=[1 3 4];
rowSize=2;
n = size(A,1);
out = A(bsxfun(@plus,(bsxfun(@plus,start',0:rowSize)-1)*n,(1:n)'));

추가 답변 (1개)

Thomas
Thomas 2012년 4월 2일
try:
A=[ 1 2 3 4 5 6 7; 8 9 10 11 12 13 14; 15 16 17 18 19 20 21];
start=[1 3 4];
rowSize=2;
B=[A(start(1),start(1):start(1)+rowSize);A(2,start(2):start(2)+rowSize);A(3,start(3):start(3)+rowSize)]

카테고리

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