finding the maximum value table A for values in table B bellow benchmark

조회 수: 2 (최근 30일)
So, here's the situation: I have three tables: A = [50 100 30 4]; B = [100 150 90 50]; C = [50 100 150];
Value in C are benchmarks and we need a table that gives for each value of C, the maximum value in A such that all values in B are bellow/equal the benchmark. That is: D = [4 50 100]; In B only 50 is bellow/equal to 50 so 4 the máximum in A. But for 100, 100/90/50 are all bellow equal to 100 so 50 is the máximum in A.
I am trying with a loop but it's not working. Thanks a lot.
  댓글 수: 2
Guillaume
Guillaume 2016년 2월 15일
Note that A, B, C, D are not tables in the matlab sense. They're just vectors, a particular type of matrices.

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

채택된 답변

Guillaume
Guillaume 2016년 2월 15일
One possible way, assuming that values in A are always positive:
AA = repmat(A', 1, numel(C));
D = max(AA .* bsxfun(@le, B', C))
If you want it to work even with negative values in A, it's only slightly more complicated
AA = repmat(A', 1, numel(C));
D = max(AA .* (0./bsxfun(@le, B', C) + 1)) %0./x+1 change a logical matrix of [0, 1] into a matrix of [Nan, 1]
  댓글 수: 3
Guillaume
Guillaume 2016년 2월 15일
For the first version of the code:
  • the transpose of A is replicated in columns as many times as there are elements in C
  • bsxfun forms a 2d matrix by comparing B to C using the le function (i.e. <=). Each row corresponds to an element of B, each column to an element of C. Each element (i, j) of the matrix is either 0 (for Bi > Cj) or 1 (for Bi <= Cj)
  • This matrix of 0 and 1 is then multiplied to the replicated and transpose version of A. This result in a matrix where for each column you have the original elements of A when B is smaller than the correspond element of C for that column, or 0 when B is greater.
  • The max function then find the maximum of each column, elements in A that are not to be taken into account where changed to 0 in the previous step, so are never the maximum
The second version of the code is only modified so that instead of a matrix of 0 and 1 you get a matrix of NaN and 1. An element of A multiplied by NaN still give NaN and max ignores NaN.
Guillaume
Guillaume 2016년 2월 15일
"Got this error: Error using bsxfun Non-singleton dimensions of the two input arrays must match each other."
Then, B or C are not vectors as in your question. At least one of them is 2D (or ND).

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

추가 답변 (0개)

카테고리

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