Doubt about finding the nearest values between array and a matrix

2 Ansichten (letzte 30 Tage)
Paulo Cunha am 25 Jan. 2022
Kommentiert: Paulo Cunha am 26 Jan. 2022
Hi, everybody
I'm trying to find the nearest values from a array inside a matrix. Example:
Array = [12, 16, 300, 200, 250, 380, 145, 6, 8, 10, 12, 100, 16, 440]; %array with 14 elements
Matrix = [15, 20, 310; 1000, 500, 1; 146, 10, 11; 5, 23, 800; 600, 100, 50]; %matrix 5x3
but when a try:
for i=1:size(Array,2)
[~,ID] = min(abs(Matrix - Array(i)),[],1);
end
The ID have just 3 elements, not 14. I don't understand why. Anybody could explain to me. please.
Att,
Paulo
0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Torsten am 25 Jan. 2022
for i=1:size(Array,2)
[r{i},c{i}] = find(abs(Matrix-Array(i))==min(abs(Matrix(:)-Array(i))));
end
1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Paulo Cunha am 26 Jan. 2022
Man, you just destroyed the question! That was incredible!! Thank you very much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jon am 25 Jan. 2022
You are overwriting the value of ID with each pass through your loop, so you only see the value for the last pass.
If you want the value for every pass then you need to assign ID(i) in the loop
5 Kommentare3 ältere Kommentare anzeigen3 ältere Kommentare ausblenden
Paulo Cunha am 25 Jan. 2022
@DGM I gave those names, because the names I use in my original project could turn the problem too complex. My mother language is portuguese, and I use it to create the variables, and the project has almost 1000 lines.
Paulo Cunha am 26 Jan. 2022
@Jon thank you for the clarification! You helped me to solve the problem with your main answer. Thank you!!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices 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!

Translated by