How do I calculate the cross product of two vectors, when the first vector is an element of a N-array and the second vector is an element of an NxD matrix;

2 次查看(过去 30 天)
% The N-array vector initialization:
r1=zeros(i,:); % i: varies from 0 to 360
% The NxD matrix initialization:
r2=zeros(i,j,:); % i: varies from 0 to 360 and j: varies from 10 to 250
% A double for loop is used and it contains the cross product of the
% two:
for i=0:1:360
for j=10:1:250
c=cross(r1(i,:),r2(i,j,:))
end
end
% The error is that Matrices are not of the same size.

回答(1 个)

Torsten
Torsten 2024-3-2
移动:Torsten 2024-3-2
r1 = rand(30,3);
r2 = rand(30,50,3);
for i=1:30
for j=1:50
c(i,j,:)=cross(r1(i,:),squeeze(r2(i,j,:)));
end
end
  4 个评论
Paul
Paul 2024-3-2
cross can work on multiple vectors, so a single loop can be used, for whatever that's worth
rng(100)
r1 = rand(30,3);
r2 = rand(30,50,3);
for i=1:30
for j=1:50
c(i,j,:)=cross(r1(i,:),squeeze(r2(i,j,:)));
end
end
for j = 1:50
cc(:,j,:) = cross(r1,squeeze(r2(:,j,:)),2);
end
Or no loop using some extra memory, also for whatever that's worth.
ccc = cross(repmat(reshape(r1,30,1,3),[1 50]),r2);
isequal(c,cc,ccc)
ans = logical
1

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by