Maybe a colon operator
Show older comments
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
Accepted Answer
More Answers (1)
N = 10 ;
A = rand(N,1) ;
i = 2:N-1 ;
B = A(i-1)+A(i+1);
1 Comment
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.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!