MATLAB Matrix dimensional error in numerical integration

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
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
 
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