MATLAB MATLAB Matrix dimensional error in numerical integration

AI Thread Summary
The user encountered a "Matrix dimensions must agree" error in MATLAB while attempting numerical integration using the trapezium method. The issue arose from attempting matrix operations without using element-wise operators. To resolve this, the user was advised to prefix operations with a dot, such as using ".*" for multiplication and ".^" for exponentiation. This ensures that operations are performed element-wise on vectors. The user confirmed that implementing these changes resolved the error.
sarrfriend
Messages
6
Reaction score
0
Hi,
I tried to numerically integrate an equation in MATLAB using the trapezium method. Here is the code that I wrote:

ao = 1;
X = 0:ao/10:ao;
Y = 1/sqrt((power(Ho,2)*((O_m*power(X,-1))+(O_r*power(X,-2))+(O_l*power(X,2))))-(k*power(c,2)));
age = trapz(X,Y);

where the values for O_m, O_r, O_l and k were obtained using input(). When I executed the above code, I get "Error using / Matrix dimensions must agree."

Can you tell me what the problem is?

Sarrvesh
 
Physics news on Phys.org
sarrfriend said:
Hi,
I tried to numerically integrate an equation in MATLAB using the trapezium method. Here is the code that I wrote:

ao = 1;
X = 0:ao/10:ao;
Y = 1/sqrt((power(Ho,2)*((O_m*power(X,-1))+(O_r*power(X,-2))+(O_l*power(X,2))))-(k*power(c,2)));
age = trapz(X,Y);

where the values for O_m, O_r, O_l and k were obtained using input(). When I executed the above code, I get "Error using / Matrix dimensions must agree."

Can you tell me what the problem is?

Sarrvesh

Hey sarrfriend.

MATLABs main data structure is a matrix and it treats pretty much everything in that way. This means that if you do say a * b, a + b and so on, then it assumes that this is going to be a matrix operation and it also assumes that the operations do things in terms of matrix assumptions (AxB a is axb, B is bxc and so on). This is why you get the error.

What you need to do if you want to do a component by component arithmetic operation is put a "." before the operation. For example let's say we have a vector A [0,1,2,3,4,5] and another vector B [0,2,4,6,8,10]. Then if we write C = A .* B we get [0,2,8,18,32,50]. If you want to do exponentiation just use .^ operator instead of power which will do a component wise exponentiation.

If you want to know more create a few row vectors of the same size and try .* ./ and .^ and see what you get in the output.
 
Hi Chiro,
Thanks the info. It worked.

Sarrfriend
 

Similar threads

Back
Top