## Cross Product of an Array

### Hollis Williams (view profile)

on 22 Apr 2019
Latest activity Commented on by James Tursa

on 22 Apr 2019

### James Tursa (view profile)

I have an array of size 3 x 100 and I basically want to create a new array where I take each column vector in the array and compute the cross product with the same vector each time to create another array of size 3 x 100, so in this case I take every vector and form the cross product with [0 0 1]'. What would be the easiest way of doing this?

R2018b

### James Tursa (view profile)

on 22 Apr 2019
Edited by James Tursa

### James Tursa (view profile)

on 22 Apr 2019

result = cross(M,repmat(v,1,size(M,2)));

James Tursa

### James Tursa (view profile)

on 22 Apr 2019
This is what I get:
>> M = rand(3,100);
>> v = rand(3,1);
>> size(repmat(v,1,size(M,2)))
ans =
3 100
I have no idea why you would be getting a 3x300 result. Did you actually run the size(M) and size(v) commands at the MATLAB prompt, or are you just reporting to me what you think they are? Actually type this in and see what you get
size(M)
size(v)
Hollis Williams

### Hollis Williams (view profile)

on 22 Apr 2019
Yes, I was using the size() command but made a typo, it is working now. I have created three 1 x 100 arrays, is it possible to put these together into one 3 x 100 array? So if A,B,C are all 1 x 100 arrays, I would need
A
B
C
James Tursa

### James Tursa (view profile)

on 22 Apr 2019
result = [A;B;C];

on 22 Apr 2019
Edited by Matt J

### Matt J (view profile)

on 22 Apr 2019

This way avoids repmatting, which may be desirable when N is large.
result=xprodmat(v)*M./vecnorm(M);
where
function A=xprodmat(a)
%Matrix representation of a cross product
%
% A=xprodmat(a)
%
%in:
%
% a: 3D vector
%
%out:
%
% A: a matrix such that A*b=cross(a,b)
if length(a)<3, error 'Input must be a vector of length 3'; end
ax=a(1);
ay=a(2);
az=a(3);
A=zeros(3);
A(2,1)=az; A(1,2)=-az;
A(3,1)=-ay; A(1,3)=ay;
A(3,2)=ax; A(2,3)=-ax;
end

Hollis Williams

### Hollis Williams (view profile)

on 22 Apr 2019
I don't think repmatting is the thing which is most computationally costly in my code but I will bear this in mind to see if I need to save time later on, thanks a lot.