Find/return value from each row in a big matrix that corresponds with a condition/value
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (4)
Cris LaPierre
am 10 Aug. 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 Kommentare
Cris LaPierre
am 10 Aug. 2020
Bearbeitet: Cris LaPierre
am 10 Aug. 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)
Bruno Luong
am 10 Aug. 2020
Bearbeitet: Bruno Luong
am 10 Aug. 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)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!