# Index exceeds the number of array elements. Index must not exceed 1

8 views (last 30 days)
sepideh on 4 Jul 2024
Answered: Umar on 4 Jul 2024
I dont understand why it stops after the first iteration and gives this error:
"Index exceeds the number of array elements. Index must not exceed 1"
g=9.8
nu= 10^-6 ;
c=1/2 ;
var_Y=0.1;
I_Y= 2.8;
s= 5;
C_beta=zeros(s)
C_Y=zeros(s)
S=0:1:4
for i=1:s
C_Y= (var_Y^2)*exp(abs(-S(i)./I_Y))
C_beta= (1/ (exp(c*var_y^2)))* ( ( exp(0.5*c*(c+1)*((var_y)^2) ) -1 )^2- c*(c+1) *(exp(0.5*c*(c+1)*(var_y)^2)-1)*(exp(var_y^2)-1)+(c^2)*(exp(C_Y(i))-1) )
plot (S,C_beta)
end

Aquatris on 4 Jul 2024
Edited: Aquatris on 4 Jul 2024
You are overwriting the C_Y array in your for loop. You initialize C_Y as a 5x5 zeros matrix and in the first iteration of your for loop, it becomes a 1x1 scalar.
g=9.8 ;
nu= 10^-6 ;
c=1/2 ;
var_Y=0.1;
I_Y= 2.8;
s= 5;
C_beta=zeros(1,s); % I think you want 1x5 not 5x5
C_Y=zeros(1,s) ; % THIS IS OVERWRITTEN IN YOUR FOR LOOP
S=0:1:4;
for i=1:s
C_Y(i)= (var_Y^2)*exp(abs(-S(i)./I_Y)); % SO CHANGE HERE TO STORE C_Y(i) instead of C_Y
C_beta(i)= (1/ (exp(c*var_Y^2)))* ((exp(0.5*c*(c+1)*((var_Y)^2))-1)^2- c*(c+1) *(exp(0.5*c*(c+1)*(var_Y)^2)-1)*(exp(var_Y^2)-1)+(c^2)*(exp(C_Y(i))-1) );
end
plot (S,C_beta);

Edited: Aditya on 4 Jul 2024
Hi Sepideh,
The error "Index exceeds the number of array elements. Index must not exceed 1" is likely due to an indexing issue in your loop. Specifically, the variable S is defined as a row vector with 5 elements, but you are trying to access S(i) where i ranges from 1 to s. However, your loop should iterate over the length of S instead of s.
1. C_Y and C_beta should be updated correctly inside the loop.
2. var_y should be var_Y for consistency.
3. The plot should be outside the loop to avoid overwriting it in each iteration.
Here is how you can update your code:
g = 9.8;
nu = 10^-6;
c = 1/2;
var_Y = 0.1;
I_Y = 2.8;
s = 5;
C_beta = zeros(1, s);
C_Y = zeros(1, s);
S = 0:1:4;
for i = 1:length(S)
C_Y(i) = (var_Y^2) * exp(abs(-S(i) / I_Y));
C_beta(i) = (1 / (exp(c * var_Y^2))) * ...
((exp(0.5 * c * (c + 1) * (var_Y^2)) - 1)^2 - ...
c * (c + 1) * (exp(0.5 * c * (c + 1) * (var_Y^2)) - 1) * ...
(exp(var_Y^2) - 1) + ...
(c^2) * (exp(C_Y(i)) - 1));
end
plot(S, C_beta);
I hope this resolves the issue that you are facing!

Umar on 4 Jul 2024
Hi Sepideh,
After analyzing your code, it seems the variables C_Y and C_beta are being reassigned in each iteration without considering the previous values. This leads to incorrect indexing and array size mismatch errors.To resolve the issue and ensure proper calculation and plotting of C_beta, you need to modify the code to update specific elements of the arrays C_Y and C_beta in each iteration.
C_beta = zeros(s, 1); C_Y = zeros(s, 1);