Arrays have incompatible sizes for this operation , ERROR help me fix the code

2 visualizzazioni (ultimi 30 giorni)
% Define the variables
clc
w = 2*pi; % angular frequency
L = 1; % length of domain
f = @(x) x.^2; % function to be expanded
g = @(x) x; % another function to be expanded
% Define the function y(x,t)
% Calculate the A_n coefficients
n = 20; % number of terms in the expansion
A = zeros(1, n);
for i = 1:n
A(i) = 2/L*integral(@(x) f(x).*sin(i*pi*x/L), 0, L);
end
% Calculate the B_n coefficients
B = zeros(1, n);
for i = 1:n
B(i) = 2/(w*L)*integral(@(x) g(x).*sin(i*pi*x/L), 0, L);
end
% Define the function y(x,t)
y = @(x,t)sum(((A.*cos(w*t.*(1:n)) + B.*sin(w*t.*(1:n))).*sin(((1:n).*pi.*x/L))));
% Plot the function over a range of x and t values
x = linspace(0, L, 100);
t = linspace(0, 10, 100);
[X,T] = meshgrid(x,t);
Y = y(X,T);
surf(X,T,Y);
xlabel('x'); ylabel('t'); zlabel('y(x,t)');

Risposta accettata

Abhinav
Abhinav il 19 Gen 2023
Modificato: Abhinav il 19 Gen 2023
The line
y = @(x,t)sum(((A.*cos(w*t.*(1:n)) + B.*sin(w*t.*(1:n))).*sin(((1:n).*pi.*x/L))))
is cause of the error, t is a 1x100 array you multiplying it with (1:n) (which is 1x20 array) that is why you are getting the matrix dimension mismatch error. Changing n to 100 resolves the error.
Refer to the following documentation link to learn more about compatible array sizes for basic operation
  1 Commento
Reham
Reham il 19 Gen 2023
can you help me with this error
Error using surf (line 71)
Z must be a matrix, not a scalar or vector.
Error in Untitled (line 29)
surf(X,T,Y);
it appears when i run the code

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by