Possible to modify only one portion of an array in one line?

3 ビュー (過去 30 日間)
Eugenio Gil
Eugenio Gil 2019 年 11 月 1 日
コメント済み: Eugenio Gil 2019 年 11 月 1 日
I have large arrays (10 to 100k elements) and would like to change some values that are too high, but only after certain point. What I have in mind is something like this:
x = [100 80 70 20 40 10 50 1 60] ;
xMax = 30 ;
transition = 3 ;
x(x>xMax & x(i)>transition) = xMax
I would like to know if there is a more efficient and elegant way of doing it instead of with a loop, like this:
x = [100 80 70 20 40 10 50 1 60] ;
xMax = 30 ;
transition = 3 ;
for i = 1 :length(x)
if i > transition & x(i) > xMax
x(i) = xMax ;
end
end
Is it possible to include two conditions in this manner?
Thanks

採用された回答

Fabio Freschi
Fabio Freschi 2019 年 11 月 1 日
x(x > xMax & 1:length(x) > transition) = xMax

その他の回答 (1 件)

Guillaume
Guillaume 2019 年 11 月 1 日
編集済み: Guillaume 2019 年 11 月 1 日
x(transition:end) = min(x(transition:end), xMax)
will be more efficient (than the now accepted answer) since it only test the condition values.
your loop is a bit siily. Since you know where the transition is you could just iterate from there:
for i = transition:numel(x)
if x(i) > xMax
x(i) = xMax
end
end
Why bother iterating over elements yoiu're never going to test.
  1 件のコメント
Eugenio Gil
Eugenio Gil 2019 年 11 月 1 日
That was absolutely silly indeed! Thanks for pointing that out.

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

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by