# Add an element to a 3D array

조회 수: 110 (최근 30일)
Mike Rovan 2019년 9월 25일
답변: Jos (10584) 2019년 9월 25일
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]

댓글을 달려면 로그인하십시오.

### 답변 (1개)

Jos (10584) 2019년 9월 25일
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)

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by