Find closest value to a constant in a multidimensional array column wise
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!