# Array indices must be positive integers or logical values.

68 次查看（过去 30 天）
cruxsign2021-4-19

I don't know what I'm doing wrong! I'd appreciate any help! I'm using MATLAB 2019b. It keeps giving me this error
Array indices must be positive integers or logical values.
Here is my code:
n = 32; % choose a number which is a exponent of 2
Cp = 0.24; % cal/g C
K = 0.007; % cal/(cm s C)
rho = 2.7; % g/cm3
kapp = K/(Cp*rho); % cm2/s
d = 5*100; % cm
start_temp = 1000;
t = 1*24*60*60; % (days)
T=zeros(1:numel(n));
for j = 1:n/2
T(j) = start_temp;
end
for j = n/2+1:n
T(j) = -start_temp;
end
figure(1);
x = linspace(0,d,length(T));
plot(x,T,'^')
hold on
% plot(T,n)
xlabel('distance (units)')
ylabel('Temperture (units)')
% Title('Heated Dike, Lab #3, #...days')
%%%%%% TAKE FAST FOURIER TRANSFORM (FFT) of your Temp function %%%%
% (You are now working in frequency (or in this case - wave number) space
% (This will output a coefficient in alternating sine,cos for each point)
%%%%%% here is my function
% function f = dfft(y)
% % First use standard Matlab routine to find Fourier transform of y.
% % z contains the complex coefficeints of the Fourier exponential series.
% z=fft(y);
% n = length(y);
% half=n/2;
% % This section takes the exponential series coefficients and gives the
% % coefficients of the Fourier Sine and Cosine series.
% % f(1) = constant term = average value of the function over period sampled
% % f(2) =
% for i = 1:2:n
% j=(i+1)/2;
% f(i)=real(z(j))/half;
% f(i+1)=-imag(z(j))/half;
% end
% j=n/2 +1;
% f(2)=real(z(j))/half;
y=dfft(T);
%%%%% GET FOURIER COEFFICIENTS (Bo, An, Bn) %%%%%%
COEFF(1) = y(1)/2;
COEFF(2) = y(2)/2;
for j = 3:2:n % increment from 3 to n by 2's
COEFF(j) = y(j);
COEFF(j+1) = y(j+1);
end
%%%%%% SOLVE FOR TEMPERATURE CHANGE using solution to heatflow eqn %%%%%
% Y = exp(1i*pi)
%
for j = 3:2:n
NEWT(j) = y(j).*exp(-kapp*t(2*pi*j/(2*d))^2)*(sin((pi*j)));
NEWT(j+1) = y(j+1).*exp(-kapp*t(2*pi*j/(2*d))^2)*(sin((pi*j)));
end
NEWT = T(2)*exp(-kapp*t(2*pi*j/(2*d))^2)*(sin((pi*j)));
##### 2 个评论显示隐藏 1更早的评论
cruxsign 2021-4-19
here is the line it gives the error
NEWT(j) = y(j).*exp(-kapp*t(2*pi*j/(2*d))^2)*(sin((pi*j)));

### 采纳的回答

I think this is the error
t(2*pi*j/(2*d))
The first time through the loop, j=3, which means
2*pi*j/(2*d) = 0.02
It's trying to index the 0.02'th entry in t, but t is a scalar. Perhaps, did you mean to multiply t by the parenethesis? Like this:
t*(2*pi*j/(2*d))
##### 3 个评论显示隐藏 2更早的评论
cruxsign 2021-4-19
Thanks again! Sure!

### Community Treasure Hunt

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

Start Hunting!

Translated by