why do i get error using * ?
46 次查看(过去 30 天)
显示 更早的评论
I want to write the code for an integral equation. i wrote it as
integrand = @(beta) (3 * (1 + cos(beta1) .* ((beta2 - beta) .* sin(beta - cos(beta)))).^2 * (beta2 - beta) * cos(beta)) ./ (2 * E * L * (sin(beta + (beta2 - beta) * cos(beta))).^3);
k_b_inv = integral(integrand, phi, beta1); but keep getting an error that says; Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication. hwo do i write this code correctly?
0 个评论
采纳的回答
Jaimin
2024-12-3,6:46
The error you are experiencing is due to the incorrect application of the element-wise multiplication operator “ .* " in your integrand function. In MATLAB, when performing element-wise operations within an anonymous function, it's essential to use “.*" for element-wise multiplication, “./” for element-wise division, and “.^” for element-wise exponentiation.
Kindly refer following code snippet for understanding.
% Define the integrand as an anonymous function
integrand = @(beta) (3 * (1 + cos(beta1) .* ((beta2 - beta) .* sin(beta - cos(beta)))).^2 .* (beta2 - beta) .* cos(beta)) ./ ...
(2 * E * L * (sin(beta + (beta2 - beta) .* cos(beta))).^3);
% Perform the integration
k_b_inv = integral(integrand, phi, beta1);
For more information kindly refer following MathWorks documentation.
0 个评论
更多回答(1 个)
Walter Roberson
2024-12-3,6:54
integral() always passes a vector of values to the function being integrated (unless 'ArrayValued' is set to true).
So in
integrand = @(beta) (3 * (1 + cos(beta1) .* ((beta2 - beta) .* sin(beta - cos(beta)))).^2 * (beta2 - beta) * cos(beta)) ./ (2 * E * L * (sin(beta + (beta2 - beta) * cos(beta))).^3);
beta is going to be a vector of values.
The first expression (3 * (1 + cos(beta1) .* ((beta2 - beta) .* sin(beta - cos(beta)))).^2 works fine, and the second expression (beta2 - beta) works fine in itself. But you have joined those two with a * operator, which is the algebraic matrix multiplication operator. If beta is passed as an N x 1 array, then the first expression would be an N x 1 array, and the (beta2 - beta) would be an N x 1 array, but you cannot use * between two N x 1 arrays. The * operator requires that the second dimension of the first parameter must match the first dimension of the second parameter -- (N x M) * (M x P) giving an N x P result. With two N x 1, the 1 that is the second dimension of the first parameter does not match the N that is the first dimension of the second parameter, and the * operator fails.
You wanted the .* operator there instead of the * operator.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!