Add an element to a 3D array

95 views (last 30 days)
Mike Rovan
Mike Rovan on 25 Sep 2019
Answered: Jos (10584) on 25 Sep 2019
I want to add to a 3D array using a for loop without changing the previous values. I created an empty 3D array by writing:
Array= zeros(0,0,100);
Then i wrote a for loop to append to that array the index number of when the if statement is satisfied, in the correct 3rd dimension
for 3Dimages=1:100
for i=1:512*inputofuser
if Original3Dimage(i,:,3Dimages)==0
Array=[Array(:,:,3Dimages),i];
else
break
end
end
end
I know if this was 2D, it could be done by saying Array=[Array,i] but i want this to be done in 3D such that depending on which of the 1:100 3Dimages the for loop is in, it creates a row of i values in the same 1:100 3Dimages page of the Array.
Example:
when 3Dimages=1
lets say the true statement occurs at an i value of 1,2,3,4,5
then when 3Dimages=2, the true statement occurs at an i value of 6,7
then when 3Dimages=3, the true statement occurs at an i value of 10,11,12
therfore Array in this 3Dimages=1:3 smaller example would have a size of 1 5 3 where:
(:,:,1)= [1 2 3 4 5]
(:,:,2)= [6 7 blank blank blank]
(:,:,3)= [10 11 12 blank blank]

Answers (1)

Jos (10584)
Jos (10584) on 25 Sep 2019
To concatenate two arrays A and B in the third dimension, use cat
cat(3, A, B)
Note that all the other dimensions of A and B should match (which does not seem to be the case in your example, at first sight). And, by the way:
% [A ; B] <-> cat(1, A, B)
% [A B] <-> cat (2, A, B)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!