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))

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