MATLAB Answers

Making a 3D Matrix and Adding Matrices to make a bigger matrix

7 views (last 30 days)
hamzah khan
hamzah khan on 9 Nov 2019
Edited: Fabio Freschi on 10 Nov 2019
Hello Guys, I have a small problem with the error in my for loop.
I am making a 3D matrix and afterwards using nested for loops to make a bigger matrix. here is my code. It is giving me the error
" Index in position 3 is invalid. Array indices must be positive integers or logical values."
I am writing my code:
B = [ 1 -1;
-1 1];
C = [ 2 -2;
-2 2];
D = [ 3 -3;
-3 3];
T = zeros(4,4)
d(:,:,1) = B;
d(:,:,2) = C;
d(:,:,3) = D;
for k = 1:1:3
for i = 1:1:2
for j = 1:1:2
T(i+k-1,j+k-1) = d(i,j,k-1);

Answers (1)

Fabio Freschi
Fabio Freschi on 10 Nov 2019
Edited: Fabio Freschi on 10 Nov 2019
In the loop, you wrote
T(i+k-1,j+k-1) = d(i,j,k-1);
k starts from one, so you are trying to access the d(i,j,0) element that does not exists.
What is the expected output you want?

Community Treasure Hunt

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

Start Hunting!