A(I): index out of bounds; value 6 out of bound 5. How to fix this error?

1 回表示 (過去 30 日間)
Steven Gangano
Steven Gangano 2022 年 2 月 24 日
回答済み: KSSV 2022 年 2 月 24 日
%I'm trying to subtract the 2nd element from the 1st element
%The answer should be: 4-2=2, 6-4=2, 8-6=2, 10-8=2
a = [2:2:10];
b = [1:length(a)];
for index = a
a(b) = a(b+1) - a(b);
end

回答 (1 件)

KSSV
KSSV 2022 年 2 月 24 日
a = [2:2:10];
b = zeros(1,length(a)-1);
for i = 1:length(a)-1
b(i) = a(i+1) - a(i);
end
Or Simply:
b = diff(a)
b = 1×4
2 2 2 2

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by