How can I vectorise the next for - loop?
1 次查看(过去 30 天)
显示 更早的评论
Hello, I have the following for loop and I would like to know if there is a way to vectorise it:
JM = 91;
stepVec = 10;
JN = 100;
x = zeros(JM,JM);
y = zeros(JM,JM);
z = zeros(JM,JM);
v = zeros(1,3,JN);
kk=1;
for i=1:stepVec:JM
for ii=1:stepVec:JM
theta=ii*pi/180;
phi=i*pi/180;
x(i,ii) = r*sin(theta)*sin(phi);
y(i,ii) = r*sin(theta)*cos(phi);
z(i,ii) = r*cos(theta);
v(:,:,kk) = [x(i,ii) y(i,ii) z(i,ii)];
kk=kk+1;
end
end
Thank you for your answers, I would like to know if I can vectorise the next two too, although I don't think it's possible.
Rotat = zeros(4,4,length(t));
RotatVector = cell(1, JN);
F = struct('cdata',cell(1,length(t)),'colormap',cell(1,length(t)));
Faxis = cell(1,JN);
for j=1:JN
for i=1:length(t)
RR = makehgtform('axisrotate',[v(1,1,j) v(1,2,j) v(1,3,j)],i*beta);
set(hgtc,'Matrix',RR);
Rotat(:,:,i) = RR;
RotatVector{1,j} = Rotat;
width = 300;
height = 225;
F(i) = getframe(gcf,[140 109.5 width height]);
Faxis{j} = F;
drawnow;
end
end
% --------------------------------------------------------------------------
grayFrame = zeros(282,375,length(F));
grayFrameNEW = cell(1,JN);
meanGrayLevels = cell (1,length(F));
meanGrayLevelsCELL = cell(1,length(F),JN);
for j=1:JN
for i=1:length(F)
% convert the image to a frame
grayFrame(:,:,i) = rgb2gray(Faxis{j}(i).cdata);
grayFrameNEW{j}=grayFrame;
% Calculate the mean gray level
meanGrayLevels{i} = mean2(grayFrameNEW{1,j}(:,:,i));
meanGrayLevelsCELL(:,:,j) = meanGrayLevels;
end
end
2 个评论
Walter Roberson
2019-1-16
You cannot vectorize getframe(), so you will not be able to avoid looping for that.
However, your line
Faxis{j} = F;
should be after the "for i" loop.
采纳的回答
Walter Roberson
2019-1-16
for i=1:stepVec:JM
for ii=1:stepVec:JM
theta=ii*pi/180;
phi=i*pi/180;
x(i,ii) = r*sin(theta)*sin(phi);
y(i,ii) = r*sin(theta)*cos(phi);
z(i,ii) = r*cos(theta);
v(:,:,kk) = [x(i,ii) y(i,ii) z(i,ii)];
kk=kk+1;
end
end
can be replaced with
angles = (1:stepVec:JM) * pi/180;
sinang = sin(angles);
cosang = cos(angles);
nang = length(angles);
rsin = r * sinang;
rcos = r * cosang;
k = 1;
for i = 1 : nang
x(i, :) = rsin(i) * sinang;
y(i, :) = rsin(i) * cosang;
z(i, :) = rcos;
v(1, :, k:k+nang-1) = [x y z];
k = k + nang;
end
and this can be further vectorized:
angles = (1:stepVec:JM) * pi/180;
nang = length(angles);
[sTheta, sPhi] = ndgrid(sin(angles));
[cTheta, cPhi] = ndgrid(cos(angles));
v = r .* [sTheta(:) .* sPhi(:), sTheta(:) .* cPhi(:), cTheta(:)]; %(nang^2) x 3 x 1
v = permute(v, [3 1 2]); %1 x 3 x (nang^2)
7 个评论
Walter Roberson
2019-1-18
You can initialize
meanGrayLevels = zeros(length(t), JN);
Then as you capture a frame into F (probably without index),
meanGrayLevels(i, j) = mean2( rgb2gray(F.cdata) );
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!