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

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Rik
Rik el 28 de Jun. de 2018
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])

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by