フィルターのクリア

In a for loop, how do I combine rows when values are equal?

4 ビュー (過去 30 日間)
balsip
balsip 2017 年 5 月 8 日
コメント済み: balsip 2017 年 5 月 8 日
I'm having trouble with the syntax of a for loop. In a vector, A, rows sometimes repeat values in succession. What I'd like to do is take the mean of the repeating rows' values only if they are neighboring, and leave the repeating rows' values that have now been averaged into one row as NaNs. In other words, I also need the length of the vector to stay the same.
This is the beginning of something that may work with some edits, but I have full confidence that the Matlab community has a more elegant approach. Also, I have a suspicion that there are downsides to this code that I'm not anticipating.
for i=1:length(A)-1; % -1 is to avoid an out of bounds error when attempting to access one beyond the last index.
if A(i) + A(i+1) == A(i) * 2;
A(i)=mean(A(i:i+1));
A(i+1)=NaN;
end
end
How can this code be improved?

採用された回答

Jan
Jan 2017 年 5 月 8 日
for k = 1:length(A)-1
if A(i) == A(i+1)
% A(i) = mean(A(i:i+1)); % Omit this! The mean of two equal value is the value itself
A(i+1) = NaN;
end
end
Why do you create the mean, if the values are equal? What should happen if a value is repeated mutliple times? Perhaps this is smarter:
index = [false; (diff(A(:)) == 0)];
A(index) = NaN;
  1 件のコメント
balsip
balsip 2017 年 5 月 8 日
Jan,
Thanks for providing your answer. Much appreciated.
To answer your question, other vectors (let's just call them vectors B and C) with values corresponding to the equal vector A (i) and (i+1) values need to be averaged when A has two repeating values. Those values in vectors B and C will not be equal.
Vectors B and C are the same length as A, and must stay the same length.
Note: I learned Matlab using vectors, and not matrices. I am seeing the inefficiency of this approach daily, but I'm waiting for a window to rewrite my code using matrices.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by