由于for循环次数过多,我经常会遇到缓慢的Matlab处理问题。 也许你可以帮助我这个例子,这在其他情况下也会帮助我:是否可以将它完全转移到矩阵中?
R = [1 2 3; 1 2 3; 1 2 3];
u1 = 200; u2 = 300; v1 = 100; v2 = 222; w1 = 123; w2 = 312;
px = 20; py = 30; pz = 25;
a = 20; b = 30; c = 25;
Ellipse = zeros(500,600,500)
for i=u1:u2
for j=v1:v2
for k=w1:w2
x=[i-px;j-py;k-pz];
x=R*x;
if (x(1)/a)^2+(x(2)/b)^2+(x(3)/c)^2<1
Ellipse(i,j,k)=1;
end
end
end
end
答案 0 :(得分:1)
这是一种运行速度快2个数量级的方法
R = [1 2 3; 1 2 3; 1 2 3];
u1 = 200; u2 = 300; v1 = 100; v2 = 222; w1 = 123; w2 = 312;
px = 20; py = 30; pz = 25;
a = 20; b = 30; c = 25;
Ellipse = zeros(500,600,500);
% Create mesh of points to process
vx = (u1:u2) - px;
vy = (v1:v2) - py;
vz = (w1:w2) - pz;
[X,Y,Z] = meshgrid(vx, vy, vz);
% Compute R*x
V = [X(:)'; Y(:)'; Z(:)'];
V = R * V;
% Divide by ellipse axes
M = diag([1/a, 1/b, 1/c]);
V = M * V;
% Determine if norm criteria is met
index = norm(V') < 1;
Ellipse(X(index), Y(index), Z(index)) = 1;
同意@Dan,一个较小的工作示例会使测试变得更容易。
答案 1 :(得分:0)
如果你做的不仅仅是简单的数学运算,那么矩阵可能会很棘手。 在这里你可以(应该)减小Ellipse的大小,因为你没有使用它的大部分条目。 你所需要的只是(101,123,190)并且事情会快得多,特别是你访问矩阵条目的方式,记住MATLAB最终会将矩阵存储为一个数组。
答案 2 :(得分:0)
@dpmcmlxxvi非常感谢您的回答。首先,抱歉这个大例子。我使用了你的答案进行了一些修改,因为norm(XY)
对我来说不起作用。(较小的例子和值适合于正常运行)
R = [1 2 3; 1 2 3; 1 2 3];
u1 = 50; u2 = 90; v1 = 20; v2 = 50; w1 = 30; w2 = 60;
px = 60; py = 25; pz = 50;
a = 10; b = 20; c = 15;
Ellipse = zeros(100,200,100);
% Create mesh of points to process
vx = (u1:u2) - px;
vy = (v1:v2) - py;
vz = (w1:w2) - pz;
[X,Y,Z] = meshgrid(vx, vy, vz);
% Compute R*x
V = [X(:)'; Y(:)'; Z(:)'];
V = R * V;
% Divide by ellipse axes
M = diag([1/a, 1/b, 1/c]);
V = M * V;
% Apply criteria
Vsq = V.*V;
crit = Vsq(1,:)+Vsq(2,:)+Vsq(3,:);
% Look for indices in the meshgrid fullfilling criteria
xe = X(find(crit<1));
ye = Y(find(crit<1));
ze = Z(find(crit<1));
xi = ceil(abs(xe+px));
yi = ceil(abs(ye+py));
zi = ceil(abs(ze+pz));
% Set values at correpsonding indices to 1
linind = sub2ind(size(Ellipse),xi,yi,zi);
Ellipse(linind) = 1;
它工作正常,所有for循环都已删除。