取一组随机坐标(x,y,z),它将成为我的3x3x3矩阵的中心(也被视为局部最小值)。我有一个函数J,它接受那些坐标,进行计算并返回一个数字。如果这26个点中的任何一个更小,那将是我下一个矩阵的中心。如果我找不到更小的值,矩阵的半径增加1,我们再次运行循环。我的问题是:如何仅通过" shell"多维数据集,而不是为之前测试的值调用函数?
我试图在下面说明它(这里是2d,但你明白了)..点是经过测试的值,"?"是需要计算并与当地最小值进行比较的那些。
这是代码
minim=100;
%%the initial size of the search matrix 2*level +1
level=1;
x=input('Enter the starting coordinate for X : ');
y=input('Enter the starting coordinate for Y : ');
z=input('Enter the starting coordinate for Z : ');
%%The loop
if(level<=10)
for m=x-level:x+level
for n=y-level:y+level
for p=z-level:z+level
A(m,n,p)=J(m,n,p);
if A(m,n,p)<minim
minim=A(m,n,p);
x=m;y=n;z=p;
level=1;
else
level=level+1;
%<<----shell loop here ---->>
end
end
end
end
else
%Display global min
display(minim, 'Minim');
%Coordinates of the global min
[r,c,d] = ind2sub(size(A),find(A ==minim));
display(r,'X');
display(c,'Y');
display(d,'Z');
end
答案 0 :(得分:1)
您可以使用逻辑索引,但我不确定您是否会通过这样做获得速度。重建min的位置有点尴尬,但是像这样你可以摆脱所有的for循环。
A = rand(7,7,7);
%"shell" mask for extraction
B = ones(5,5,5);
B = padarray(B,[1,1,1]);
B = logical(abs(B-1));
[val, ind] = min(A(B))
%reconstruct location
tmp = zeros(1,sum(B(:)));
tmp(ind) = 1;
C = zeros(size(A));
C(B) = tmp;
[~, ind] = max(C(:));
[r,c,d] = ind2sub(size(A),ind);
答案 1 :(得分:1)
这是一种可以在单个循环中访问所有“shell”元素的方法:
clear;
%// a cube matrix to play with
A=nan(5,5,5);
n=length( A(:,1,1) ); %// Assuming cube matrix
%// lets change all ot the "shell" elements to 1
for i=1:n
% 1st and nth level
A(1,i,1)=1;
A(i,1,1)=1;
A(n,i,1)=1;
A(i,n,1)=1;
A(1,i,n)=1;
A(i,1,n)=1;
A(n,i,n)=1;
A(i,n,n)=1;
% 2nd to (n-1)th level
A(1,1,i)=1;
A(1,n,i)=1;
A(n,1,i)=1;
A(n,n,i)=1;
end
请注意,角落元素不止一次到达。结果矩阵:
>> A
A(:,:,1) =
1 1 1 1 1
1 NaN NaN NaN 1
1 NaN NaN NaN 1
1 NaN NaN NaN 1
1 1 1 1 1
A(:,:,2) =
1 NaN NaN NaN 1
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
1 NaN NaN NaN 1
A(:,:,3) =
1 NaN NaN NaN 1
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
1 NaN NaN NaN 1
A(:,:,4) =
1 NaN NaN NaN 1
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
1 NaN NaN NaN 1
A(:,:,5) =
1 1 1 1 1
1 NaN NaN NaN 1
1 NaN NaN NaN 1
1 NaN NaN NaN 1
1 1 1 1 1
答案 2 :(得分:1)
这是一个简单的C ++解决方案
这是一个代表2D的5x5x5立方体:
a[i][j][0]
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
a[i][j][1]
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
a[i][j][2]
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
a[i][j][3]
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
a[i][j][4]
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
这是立方体解析的代码:
int a[5][5][5]
int matrix_size = 2*level+1;
for(int z=0;z<matrix_size;z++)
if(z==0 || z= matrix_size-1)
{
for(int i=0;i<matrix_size-1;i++)
for(int j=0;j<matrix_size-1;j++)
{
//compare minim with a[i][j][z];
}
}
else
for(int i=0;i<matrix_size-1;i++)
{
if(i==1 || i==matrix_size-1)
{
for(int j=0;j<matrix_size-1;j++)
//compare minim with a[i][j][z];
}
else
{
//compare minim with a[i][1][z] and a[i][matrix_size-1][z];
}
}