How to calculate distance between array elements?

16 ビュー (過去 30 日間)
Hajem Daham
Hajem Daham 2018 年 4 月 9 日
コメント済み: Hajem Daham 2018 年 4 月 10 日
Hi, Let say I have this array:
A = [1 3 5 1 4 1 2 6 1]
the distances between elements are:
1-3-5-1:
1 to 3 = 2
3 to 5 = 1
5 to 1 = 3
1-4-1:
1 to 4 = 2
4 to 1 = 1
1-2-6-1:
1 to 2 = 3
2 to 6 = 1
6 to 1 = 2
what I need is to accumulate the distance of elements between every two ones, and if the distance between every two ones is greater than 5 then a penalty of 3 should be added to the total distance of the whole array. For example the distance between 1-3-5-1 = 6, so in this case, a penalty of 3 should be added to the total distance and so on.
  5 件のコメント
Guillaume
Guillaume 2018 年 4 月 9 日
I'm not any clearer. How is the distance from 3 to 5 not equal to 2? And from 5 to 1 not equal to 4?
Hajem Daham
Hajem Daham 2018 年 4 月 9 日
don't focus on numbers its just example if you know how to do the coding please answer, otherwise leave it.

サインインしてコメントする。

採用された回答

Matt J
Matt J 2018 年 4 月 9 日
編集済み: Matt J 2018 年 4 月 9 日
I too find the post hard to interpret, but maybe this is what you want:
A = [1 3 5 1 4 1 2 6 1];
dist=cumsum([0 2 1 3 2 1 3 1 2]); %distances from start
onelocs=find(A==1);
D=dist(onelocs(2:end)) - dist(onelocs(1:end-1)); %distance between ones
totalDistance=dist(end) + 3*sum(D>5)
  1 件のコメント
Hajem Daham
Hajem Daham 2018 年 4 月 10 日
Thank you Matt, this is what I want.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by