brucezepplin
brucezepplin

Reputation: 9752

matlab - error with cross product

I am having an issue with the cross product function. I need to take the cross product of two vectors for each pixel, and then sum the results of all pixels.

 i=1;     
 [h,w,d] = size(current_vec);
 for pxRow = 1:h % fixed pixel row
 for pxCol = 1:w % fixed pixel column
 for pxsize = 1:d 

 for r = 1:h % row of distant pixel
 for c = 1:w % column of distant pixel
 for dpth = 1:d

 bfield(c,r,dpth) = cross(current_vec(c,r,dpth),dist_vec(c,r,dpth));                               % pythagoras theorem to get distance to each pixel                                                                     % unit vector from x to s                     

 end
 end
 end
 Bfield(i) = {bfield}; % filling a cell array with results. read below
 i = i+1;
 end
 end
 end


??? Error using ==> cross at 37
A and B must have at least one dimension of length 3.

??? Error using ==> cross at 37
A and B must have at least one dimension of length 3.

Error in ==> MAC2 at 71
bfield(c,r,dpth) = cross(current_vec(c,r,dpth),dist_vec(c,r,dpth));                               

however the offending vectors current_vec and dist_vec are the following:

>> size(current_vec)

ans =

    35    35     3

>> size(dist_vec)

ans =

    35    35     3

so as far as I'm concerned they fill the criteria to be used in a cross product. why isn't this the case?

Upvotes: 0

Views: 2752

Answers (1)

tmpearce
tmpearce

Reputation: 12693

You need to use the vectorized form of cross:

bfield = cross(current_vec,dist_vec);

cross will work on the first dimension with length of 3. The way you were doing it with nested loops, you're accessing a single element (a scalar) by indexing. You can't cross a scalar with a scalar.

Upvotes: 3

Related Questions