How to subtract the elements of an array
14 次查看(过去 30 天)
显示 更早的评论
Hello,
I am coding an .m file in MATLAB R2018a. The code I have (partial) is:
nt=[8,17,22,25]'
for i=1:3
grad(i)=nt(i+1)-nt(i)
end
sumgrad=sum(grad)
As you can see, I am trying to subtract the 2nd element of the array is subtracted to the 1st and place it on the index 1 of the array grad(i). . Then, the 3rd element of the array is subtracted to the 2nd and place it on the index 2 of the array grad(i). By last, the 4th element of the array to the 3rd and place it on the index 3 of the array grad(i)
Then, all the elements of the array grad(i) are sum into the variable sumgrad.
I am getting this error:
Error: Index exceeds array bounds.
I am quite sure there is a better way of coding this. Could someone help me?
Best regards,
Hugo
0 个评论
采纳的回答
Ameer Hamza
2020-9-10
Although your code seems correct and the error shouldn't occur, you can directly use diff() function and avoid the for-loop
nt=[8,17,22,25]';
grad = diff(nt);
sumgrad=sum(grad)
更多回答(1 个)
Matt J
2020-9-10
编辑:Matt J
2020-9-10
At which line does the error occur?The only thing I can think of is that you accidentally have a variable called "sum" previously defined in your workspace, e.g.,
sum=0;
nt=[8,17,22,25]'
for i=1:3
grad(i)=nt(i+1)-nt(i)
end
sumgrad=sum(grad)
Index exceeds the number of array elements (1).
Error in test (line 11)
sumgrad=sum(grad);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 NaNs 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!