Replace some values of a vector with values from another vector of the same size

4 ビュー (過去 30 日間)
Hi,
I have a vector of calculated values that must be capped at a certain value. The capped value may vary along the length of the vector. So, I would like to replace the values in the vector that exceed the limit with the limit value that is appropriate for that element of the vector.
I've relied on this community question for help: https://uk.mathworks.com/matlabcentral/answers/214293-replace-some-values-of-a-vector-with-another-vector-which-has-a-different-size but I'm getting an error based on different numbers of elements on each side of an assigment.
A simplified version of what I'd like to achieve is as follows:
A = [0 0 -3 -8 -10 0 0]
B = [-12 -12 -4 -4 -4 -12 -12]
k = (A < B)
C = A
C(k) = B
A is my original vector and B is a vector of limit values that A must be capped by. C should equal A except where the limit is exceed, where it should equal B.
What I'd like back is:
C = [0 0 -3 -4 -4 0 0]
But it is the last line that is throwing the error. In the workspace, all variables are 1x7 so I'm a bit confused about the error.
Thanks,
Simon.

採用された回答

Ive J
Ive J 2021 年 1 月 6 日
You've missed the fact that k is of logical class:
A = [0 0 -3 -8 -10 0 0]
B = [-12 -12 -4 -4 -4 -12 -12]
k = (A < B)
C = A
C(k) = B(k)
0 0 -3 -4 -4 0 0
  1 件のコメント
Simon Aldworth
Simon Aldworth 2021 年 1 月 6 日
Thanks. As well as the improvement from Bruno below, I can also delete the need for k by using:
A = [0 0 -3 -8 -10 0 0]
B = [-12 -12 -4 -4 -4 -12 -12]
C = A
C(A < B) = B(A < B)

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2021 年 1 月 6 日
Simply
C = max(A,B)
  2 件のコメント
Simon Aldworth
Simon Aldworth 2021 年 1 月 6 日
Thank you. I think I can use this improvement too.
Stephen23
Stephen23 2021 年 1 月 6 日
+1 this is by far the simplest and most efficient solution.

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

カテゴリ

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

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by