Find closest value to a constant in a multidimensional array column wise

조회 수: 1 (최근 30일)
toka55
toka55 2018년 6월 28일
댓글: toka55 2018년 6월 28일
I have a matrix B B(:,:,1) =
2 8
0 5
B(:,:,2) =
1 3
7 9
I want to find the index of a value close e.g. to 2.9. in each column. I tried the following code:
[r,c,v] = ind2sub(size(B),find(min(abs(B-2.9))));
I get:
r =
1
2
1
2
c =
1
1
2
2
v =
1
1
1
1
What I want is:
r = 1,2,1,1 c = 1,2,1,2 v = 1,1,2,2

채택된 답변

Rik
Rik 2018년 6월 28일
The method I used below is to separate the parts the array you want to test from the rest of the array. As you can see in the disp, the result is indeed r=[1,2,1,1] c=[1,2,1,2] v=[1,1,2,2].
B=cat(3,[2,8;0,5],[1,3;7,9]);
b=2.9;
[v,c]=meshgrid(1:size(B,3),1:size(B,2));
temp=mat2cell(B,size(B,1),ones(1,size(B,2)),ones(1,size(B,3)));
[~,row_index]=cellfun(@(x) min(abs(x-b)),temp,'uni',0);
r=cell2mat(row_index(:))';
c=c(:)';
v=v(:)';
disp([r;c;v])

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by