Maybe a colon operator
9 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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)
0 个评论
更多回答(1 个)
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
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 Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!