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

6 visualizzazioni (ultimi 30 giorni)
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

Risposte (4)

madhan ravi
madhan ravi il 10 Ago 2020
Wanted = nonzeros(x .* (abs(A - c) < 1e-2))

Cris LaPierre
Cris LaPierre il 10 Ago 2020
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 Commenti
Cris LaPierre
Cris LaPierre il 10 Ago 2020
Modificato: Cris LaPierre il 10 Ago 2020
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)

Accedi per commentare.


Erik Vabo Vatsvaag
Erik Vabo Vatsvaag il 10 Ago 2020
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 il 10 Ago 2020
Modificato: Bruno Luong il 10 Ago 2020
"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)

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by