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.
    2 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
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
% Plot the final temperature distribution
contourf(x,y,T);
colorbar;
xlabel('x');
ylabel('y');
title('Temperature distribution');
0 commentaires
Réponses (1)
  VBBV
      
      
 le 21 Déc 2022
        
      Modifié(e) : VBBV
      
      
 le 21 Déc 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)
Voir également
Catégories
				En savoir plus sur Line Plots dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

