How can I make multiple max in elegant way?

조회 수: 2 (최근 30일)
Eli Borodach
Eli Borodach 2016년 3월 10일
댓글: Walter Roberson 2016년 3월 10일
Hello all, let's assume I have 8 vectors x1,x2,x3,...,x8 I can use: max(max(max(x1,x2),x3),x4) and so on... But how can I do it in a more elegant way?
Thanks in Advance

채택된 답변

Ced
Ced 2016년 3월 10일
편집: Ced 2016년 3월 10일
you could do
max(max([ x1 x2 x3 x4 x5 .... ]))
Since the first max is evaluated along the columns, I think it should be fast enough. Alternatively, you could of course do X = [ x1 x2 x3 ... ] and then max(X(:)). That's shorter, but depending on the length of your vectors, I would go with the first option. A common alternative is to use sort, e.g.
X_sorted = sort([ x1 x2 ... ]);
xmax = max(X_sorted(end,:))
but since for max, you don't need the matrix to be fully sorted, I would guess that max is actually faster.
  댓글 수: 2
Eli Borodach
Eli Borodach 2016년 3월 10일
Thanks you very much!
Walter Roberson
Walter Roberson 2016년 3월 10일
Are you looking for the overall maximum among the 8 vectors? Or are you looking for the maximum for each entry in the vector -- e.g.,
[max([x1(1), x2(1), x3(1), x4(1), x5(1), x6(1), x7(1), x8(1)]),
max([x1(2), x2(2), x3(2), x4(2), x5(2), x6(2), x7(2), x8(2)]),
...
max([x1(end), x2(end), x3(end), x4(end), x5(end), x6(end), x7(end), x8(end)]) ];
Your max(max(max(...max(x1,x2), x3), x4 ... code is taking maximum for each entry, which is what I coded for. Some of the solutions Ced posted are for the overall maximum.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 3월 10일
If they have the same orientation but the orientation is not known ahead of time,
max( cat(3, x1, x2, x3, x4, x5, x6, x7, x8), [], 3)
The result would have the same orientation.
Or you could use
max( [x1(:), x2(:), x3(:), x4(:), x5(:), x6(:), x7(:), x8(:)], [], 2)
the result would be a column vector.
If you know that they are column vectors already you can leave out the (:)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by