Find/return value from each row in a big matrix that corresponds with a condition/value

조회 수: 5 (최근 30일)
Dear All Community members,
I have a big matrix ("A") and want to return values from an array "x" for each row when a condition/value is met in matrix A.
A simplified example is given below;
A=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1 1 1 1 1 1 1 1 1 1; 0 0.15 0.30 0.45 0.60 0.75 0.90 1 1 1 1 1 1 1 1 1 1 1 1 1 1; 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1];
x=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
Condition, c=0.9
I want to find in matrix "A" the first value that meets the condition in "c" and return the corresponding values from "x". I.e. the resulting vector shall be= 9,6,18.
Any help or tips is deeply appreciated.
Thanks in advance

답변 (4개)

madhan ravi
madhan ravi 2020년 8월 10일
Wanted = nonzeros(x .* (abs(A - c) < 1e-2))
  댓글 수: 2
Erik Vabo Vatsvaag
Erik Vabo Vatsvaag 2020년 8월 10일
Let me specify, I only want the first time the value appears in each row and if the value dont appear I want closest value.

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


Cris LaPierre
Cris LaPierre 2020년 8월 10일
Is the order of the resulting vector important?
You can just do a normal equality comparison, then use any to create a logical vector displaying if the corresponding column contains at least one true value.
A=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1 1 1 1 1 1 1 1 1 1; 0 0.15 0.30 0.45 0.60 0.75 0.90 1 1 1 1 1 1 1 1 1 1 1 1 1 1; 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1];
x=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
c=0.9;
D=A==c;
ind = any(D,1);
x(ind)
ans = 1×3
6 9 18
  댓글 수: 5
Cris LaPierre
Cris LaPierre 2020년 8월 10일
편집: Cris LaPierre 2020년 8월 10일
A=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1 1 1 1 1 1 1 1 1 1;
0 0.15 0.30 0.45 0.60 0.75 0.90 1 1 1 1 1 1 1 1 1 1 1 1 1 1;
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1];
x=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
c=0.9;
D=A-c;
% You only want greater than or equal to, so set everything less than to a large positive value
D(D<0)=999;
[~,ind] = min(D,[],2)
x(ind)

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


Erik Vabo Vatsvaag
Erik Vabo Vatsvaag 2020년 8월 10일
Sorry, let me specify.
I only want the first value equal to or bigger than c. Both your answers will be wrong if 0.9 appears more than once per row.
Thank you so much for your help!

Bruno Luong
Bruno Luong 2020년 8월 10일
편집: Bruno Luong 2020년 8월 10일
"Let me specify, I only want the first time the value appears in each row and if the value dont appear I want closest value."
Then use MIN rather than FIND, and no need to fix emperically the tolerance.
c = 0.9;
[~,col] = min(abs(A-c),[],2);
x(col)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by