# Matlab Error after executing the code

3 views (last 30 days)
venkatesu u on 4 Nov 2021
Answered: VBBV on 30 Nov 2021
I have the following Matlab code.
clear all
clc
kc=[1 2 3 4 5 6 7 8 9 0];
k12=200;
k34=300;
new1=1:1:10;
for h1=1:length(new1);
for l1=1:length(new1);
K(h1,l1)=[k12 -k12 0 0;-k12 kc(h1,l1)+k12 -kc(h1,l1) 0;0 -kc(h1,l1) k34+kc(h1,l1) -k34;0 0 -k34 k34];
end
end
After executing it, an error is displayed as "Unable to perform assignment because the left and right sides have a different number of elements." Kindly provide any suggestions to avoid this error.
##### 2 CommentsShowHide 1 older comment
venkatesu u on 4 Nov 2021
Dear Madam I have tried your code in MATLAB but it shows following error "Index in position 1 exceeds array bounds. Index must not exceed 1." Kindly provide suggestions to avoid error

Sreedevi K on 4 Nov 2021
You have to save into a cell array or a 3D matrix. As shown below:
kc=[1 2 3 4 5 6 7 8 9 0];
k12=200;
k34=300;
new1=1:1:10;
count = 0 ;
for h1=1:length(new1)
for l1=1:length(new1)
count = count+1 ;
K{count}=[k12 -k12 0 0;-k12 kc(h1,l1)+k12 -kc(h1,l1) 0;0 -kc(h1,l1) k34+kc(h1,l1) -k34;0 0 -k34 k34];
end
end

VBBV on 30 Nov 2021
clear all
clc
kc=[1 2 3 4 5 6 7 8 9 0];
k12=200;
k34=300;
new1=1:1:10;
for l1=1:length(new1)
K(:,:,:,:,l1)=[k12 -k12 0 0;-k12 kc(l1)+k12 -kc(l1) 0;0 -kc(l1) k34+kc(l1) -k34;0 0 -k34 k34];
end
K
K =
K(:,:,1,1,1) = 200 -200 0 0 -200 201 -1 0 0 -1 301 -300 0 0 -300 300 K(:,:,1,1,2) = 200 -200 0 0 -200 202 -2 0 0 -2 302 -300 0 0 -300 300 K(:,:,1,1,3) = 200 -200 0 0 -200 203 -3 0 0 -3 303 -300 0 0 -300 300 K(:,:,1,1,4) = 200 -200 0 0 -200 204 -4 0 0 -4 304 -300 0 0 -300 300 K(:,:,1,1,5) = 200 -200 0 0 -200 205 -5 0 0 -5 305 -300 0 0 -300 300 K(:,:,1,1,6) = 200 -200 0 0 -200 206 -6 0 0 -6 306 -300 0 0 -300 300 K(:,:,1,1,7) = 200 -200 0 0 -200 207 -7 0 0 -7 307 -300 0 0 -300 300 K(:,:,1,1,8) = 200 -200 0 0 -200 208 -8 0 0 -8 308 -300 0 0 -300 300 K(:,:,1,1,9) = 200 -200 0 0 -200 209 -9 0 0 -9 309 -300 0 0 -300 300 K(:,:,1,1,10) = 200 -200 0 0 -200 200 0 0 0 0 300 -300 0 0 -300 300
clear K
TT = 1
TT = 1
for l1=1:length(new1)
K{TT}=[k12 -k12 0 0;-k12 kc(l1)+k12 -kc(l1) 0;0 -kc(l1) k34+kc(l1) -k34;0 0 -k34 k34];
TT = TT+1;
end
K
K = 1×10 cell array
{4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double} {4×4 double}
You need one for loop only to compute the matrix, Also, you were getting error because, when you access more elements from matrix than its actual dimension. You can do it using cell array as below