Doubt about finding the nearest values between array and a matrix

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

 채택된 답변

Torsten
Torsten 2022년 1월 25일

1 개 추천

for i=1:size(Array,2)
[r{i},c{i}] = find(abs(Matrix-Array(i))==min(abs(Matrix(:)-Array(i))));
end

댓글 수: 1

Man, you just destroyed the question! That was incredible!! Thank you very much!

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

추가 답변 (1개)

Jon
Jon 2022년 1월 25일

1 개 추천

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

Jon
Jon 2022년 1월 25일
편집: Jon 2022년 1월 25일
Also, I'm not really clear on what you are looking for here. Do you want to know for each element of Array the value in Matrix (doesn't matter the row or column) which is the closest?
So for example for Array(1) = 12, what is the answer you are hoping to find?
I'm just going to add that clearing up this confusion would be helped greatly by using meaningful variable names. Calling an array "Array" is about as fruitful as naming your kids "Hey You".
Paulo Cunha
Paulo Cunha 2022년 1월 25일
편집: Paulo Cunha 2022년 1월 26일
@Jon I need to know the positions of the nearest values from the Array inside the Matrix. Because in my original matrix, that I'm using in my project and it has 5548 elements, has several elements with the same value, and I need to know the positions of all of them.
For Array(1) = 12, I'm waiting for (3,3). The position of 11.
@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.
@Jon thank you for the clarification! You helped me to solve the problem with your main answer. Thank you!!

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2022년 1월 25일

댓글:

2022년 1월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by