Changing array elements relative to it's size and position in the array

2 ビュー (過去 30 日間)
Tim David
Tim David 2021 年 5 月 16 日
コメント済み: Tim David 2021 年 5 月 18 日
If I have an array such as:
R = [0, 0, 4, 0, 1, 0, 0, 0, 0, 6];
I want to code it so that all elements are checked and if the number in that element is greater than the gap between it and the next non-zero element, it is reduced to the (gap distance minus 1)
IE, R(1), R(2) etc are 0 so remains 0. R(3) is checked to be 4, has a distance of 2 until the next non-zero entry so is reduced to 1. R(5) is checked to be 1, there is no non-zero entry within 1 space so it remains 1. R(10) is 6 and has a distance of 3 until the next non zero entry so is reduced to 2. etc
Sorry if that's poorly explained. I'm very new to Matlab and this one has stumped me so any help or starting points will be appreciated.
  2 件のコメント
the cyclist
the cyclist 2021 年 5 月 16 日
To clarify:
"gap distance" means "how many elements away" it is, and has nothing to do with the difference value?
Do you only look "forward" (elements toward the right, with larger index) to determine gap distance?
Also, I don't understand how 6 has a distance of 3 to the next element.
Tim David
Tim David 2021 年 5 月 16 日
yes, the gap distance means how many elements away and has nothing to do with the difference value, and you only look right.
I should have been more clear, this is a circular system so R(10) moves over to R(1) and so on and repeats, so R(10) is 3 elements away from R(3).

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

採用された回答

the cyclist
the cyclist 2021 年 5 月 16 日
編集済み: the cyclist 2021 年 5 月 16 日
I think this does what you want:
% Original data
R = [0, 0, 4, 0, 1, 0, 0, 0, 0, 6];
% Identify the non-zero elements of R
isNonZero = R>0;
nonzeroR = R(isNonZero);
% The positional index of the non-zero elements
nonZeroIndex = find(isNonZero);
% Calculate the gaps
gap = [diff(nonZeroIndex) (nonZeroIndex(1)+numel(R))-nonZeroIndex(end)];
% Reduce the non-zero values of R to (gap-1)
newNonZeroR = min(nonzeroR,gap-1);
% Re-insert the new values into the vector
R(isNonZero) = newNonZeroR;

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by