3

I have a 2x2 matrix, each element of which is a 1x5 vector. something like this:

x = 1:5;
A = [ x  x.^2; x.^2 x];

Now I want to find the determinant, but this happens

B = det(A);
Error using det
Matrix must be square.

Now I can see why this happens, MATLAB sees A as a 2x10 matrix of doubles. I want to be able to treat x as an element, not a vector. What I'd like is det(A) = x^2 - x^4, then get B = det(A) as a 1x5 vector.

How do I achieve this?

Amro
  • 123,847
  • 25
  • 243
  • 454
Eddy
  • 6,661
  • 21
  • 58
  • 71

2 Answers2

3

While Matlab has symbolic facilities, they aren't great. Instead, you really want to vectorize your operation. This can be done in a loop, or you can use ARRAYFUN for the job. It sounds like ARRAYFUN would probably be easier for your problem.

The ARRAYFUN approach:

x = 1:5;
detFunc = @(x) det([ x x^2 ; x^2 x ]);

xDet = arrayfun(detFunc, x)

Which produces:

>> xDet = arrayfun(detFunc, x)
xDet =
     0   -12   -72  -240  -600

For a more complex determinant, like your 4x4 case, I would create a separate M-file for the actual function (instead of an anonymous function as I did above), and pass it to ARRAYFUN using a function handle:

xDet = arrayfun(@mFileFunc, x);
sfstewman
  • 5,589
  • 1
  • 19
  • 26
  • Thanks, I ended up using the anonymous function approach because I couldn't get it to work otherwise. Kept spitting errors about "Not enough inputs" or something. – Eddy Jul 20 '12 at 12:24
1

Well mathematically a Determinant is only defined for a square matrix. So unless you can provide a square matrix you're not going to be able to use the determinant.

Note I know wikipedia isn't the end all resource. I'm simply providing it as I can't readily provide a print out from my college calculus book.

Update: Possible solution?

x = zeros(2,2,5);
x(1,1,:) = 1:5;
x(1,2,:) = 5:-1:1;
x(2,1,:) = 5:-1:1;
x(2,2,:) = 1:5;

for(n=1:5)
    B(n) = det(x(:,:,n));
end

Would something like that work, or are you looking to account for each vector at the same time? This method treats each 'layer' as it's own, but I have a sneaky suspiscion that you're wanting to get a single value as a result.

Ben A.
  • 1,039
  • 6
  • 13
  • The thing is, if you treat x symbolically then I do have a square matrix. What I need to figure out is how to calculate the determinant symbolically and then substitute a vector for x. – Eddy Jul 19 '12 at 15:46
  • Just a toss up off the top of my head here as a possible soultion. Updated the answer with it. – Ben A. Jul 19 '12 at 16:01
  • Although I didn't end up using this solution, it was helpful for something else I was doing with the determinant so I'm going to upvote it. – Eddy Jul 20 '12 at 12:26
  • Glad I could help a little bit at least =P – Ben A. Jul 20 '12 at 12:40