Maybe a colon operator

조회 수: 9 (최근 30일)
Manila Gomes
Manila Gomes 2017년 11월 28일
편집: Jan 2017년 11월 28일
It is possible write this for in a more fast code (maybe colon)?
for i = 2 : n-1
A(i) = A(i-1)+A(i+1);
end

채택된 답변

Birdman
Birdman 2017년 11월 28일
Vectorizing is possible and better. One approach:
A=randi([1 10],1,10)
n=numel(A);
i=2:n-1;
A(i)=A(i-1)+A(i+1)

추가 답변 (1개)

KSSV
KSSV 2017년 11월 28일
편집: KSSV 2017년 11월 28일
N = 10 ;
A = rand(N,1) ;
i = 2:N-1 ;
B = A(i-1)+A(i+1);
  댓글 수: 1
Jan
Jan 2017년 11월 28일
편집: Jan 2017년 11월 28일
Note: If N is huge, creating the index vectors explicitly is slower than:
N = 1e7;
A = rand(N, 1) ;
B = A(1:(N-2)) + A(3:N);
Here Matlab checks only for the 4 given indices, if they are inside the valid range, while for
i = 2:N-1 ;
B = A(i-1) + A(i+1);
Matlab requires 2e7-4 boundary checks.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by