필터 지우기
필터 지우기

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.

조회 수: 3 (최근 30일)
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');

답변 (1개)

VBBV
VBBV 2022년 12월 21일
편집: VBBV 2022년 12월 21일
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
VBBV
VBBV 2022년 12월 21일
편집: VBBV 2022년 12월 21일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by