I do not get how am I getting Index in position 3 is invalid. Array indices must be positive integers or logical values. in code attached.

1 visualización (últimos 30 días)
clc
clear all
% Define problem parameters
L = 0.3; % length of bar
W = 0.4; % width of bar
IMAX = 31; % number of points in x-direction
JMAX = 41; % number of points in y-direction
k = 380; % thermal conductivity
alpha = 11.234e-5; % thermal diffusivity
dt = 0.2; % time step
tf = 1; % final time
% Set up the computational grid
dx = L/(IMAX-1); % grid spacing in x-direction
dy = W/(JMAX-1); % grid spacing in y-direction
[x,y] = meshgrid(0:dx:L, 0:dy:W); % coordinates of grid points
% Set up initial and boundary conditions
T0 = 0; % initial temperature
T1 = 40; % temperature at top boundary
T2 = 0; % temperature at left boundary
T3 = 10; % temperature at right boundary
T4 = 0; % temperature at bottom boundary
T = T0*ones(IMAX,JMAX); % initialize temperature field
T(:,JMAX) = T1; % apply boundary conditions
T(1,:) = T2;
T(IMAX,:) = T3;
T(:,1) = T4;
% Set up the system of equations to be solved at each time step
A = sparse(IMAX*JMAX,IMAX*JMAX); % coefficient matrix
b = zeros(IMAX*JMAX,1); % right-hand side vector
% Loop over time steps
for t = dt:dt:tf
% Loop over grid points
for i = 2:IMAX-1
for j = 2:JMAX-1
idx = (i-1)*JMAX + j; % index of current grid point
A(idx,idx) = 1 + 4*alpha*dt/dx^2 + 4*alpha*dt/dy^2; % center coefficient
A(idx,idx-1) = -alpha*dt/dy^2; % y-left coefficient
A(idx,idx+1) = -alpha*dt/dy^2; % y-right coefficient
A(idx,idx-JMAX) = -alpha*dt/dx^2; % x-left coefficient
A(idx,idx+JMAX) = -alpha*dt/dx^2; % x-right coefficient
b(idx) = T(i,j,t); % right-hand side value
end
end
% Solve the system of equations using fsolve
Tvec = fsolve(@(Tvec) ATvec - b, T(:));
T = reshape(Tvec,IMAX,JMAX); % reshape solution vector into temperature field
end
Index in position 3 is invalid. Array indices must be positive integers or logical values.
% Plot the final temperature distribution
contourf(x,y,T);
colorbar;
xlabel('x');
ylabel('y');
title('Temperature distribution');

Respuestas (1)

VBBV
VBBV el 21 de Dic. de 2022
Editada: VBBV el 21 de Dic. de 2022
for t = dt:dt:tf % this is source
b(idx) = T(i,j,t); this is cause
Matlab uses 1 based array indexing. t is assigned decimal values as for loop index. Change it to
Step = dt:dt:tf;
for t = 1: length(Step)
  1 comentario
VBBV
VBBV el 21 de Dic. de 2022
Editada: VBBV el 21 de Dic. de 2022
Note that there is one more flaw in code. You have defined the matrix T as M x N (2D)
T = T0*ones(IMAX,JMAX);
But trying to access the same matrix using three indices, as here M x N x P (3D)
b(idx) = T(i,j,t);
This will also throw error

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by