MATLAB Why Does Matlab Say Matrix Must Be Square When Using mpower?

Click For Summary
The discussion centers on a MATLAB coding error encountered when executing a specific line of code involving matrix operations. The initial error, "Matrix must be square," arises from the use of the matrix power operator (^) on a non-square matrix. The subsequent error, "Inner matrix dimensions must agree," indicates a mismatch in dimensions during matrix multiplication. It is clarified that element-wise operations should be used instead of matrix operations for vectors, specifically by employing .^ and .* to ensure proper element-wise calculations. Additionally, debugging tips are provided, such as performing smaller calculations to isolate errors and using the size function to check dimensions. The importance of ensuring compatible dimensions for matrix multiplication is emphasized, particularly when dealing with vectors.
MathewsMD
Messages
430
Reaction score
7
When running the following code on Matlab:

>> y(i) = y(i-1) + (0.5 * y.^3 * exp(t^2 + t))*h

I get the error:

? Error using ==> mpower
Matrix must be square.

It seems fairly simple but I'm not quite sure what I'm overlooking. Any help with regards to what I may be doing wrong would be greatly appreciated!
 
Physics news on Phys.org
I've gotten to:

>> y(i) = y(i-1) + (0.5 * y.^3 * exp(t.^2 + t))*h
? Error using ==> mtimes
Inner matrix dimensions must agree.

But the code still seems to be invalid.
 
Isn't y.^3 * exp(t.^2 + t) trying to multiply two row vectors y.^3 times exp(t.^2 + t)? You need to transpose one of them or do element wise multiplication.
P.S. To debug equations, try small part calculations and see which ones abort. Also, the size function helps you see what the dimensions are.
 
Use .^ and .* instead of ^ and *. The former perform elementwise operations, which is what you want here I believe.

* works fine if at least one operand is a scalar. But if you have two vectors, or a mixture of vectors and matrices, then they need to have compatible dimensions to use * (common inner dimension, i.e. NxM * MxP)
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K