MATLAB: How to build on an existing struct 4x4xn matrix

dimensionsMATLABmatrixstruct

I have an struct, for example…
A = struct();
where we have a 4×4 matrix
A.G = rand(4,4);
I want to build on values within the (4×4) matrix but stack new values in a n'th dimension.
How do I build on the maxtrix in the n'th dimesnion if I don't know how many non-zero values exist in respective field A.G(1,1,n), A.G(1,2,n), A.G(2,2.n) and A.G(4,4,n). the n't value can stack randomly. I wan't to know how many non-zero values lies behind for example A.G.(1,2,n) where n is a unkown value depending how many values i already put into A.G(1,2,n), which i don't keep track on.

Best Answer

Hello Happy PhD,
Try this one...
clc;
clear all;
A.G(:,:,1) = [1 2 1 1 ; 4 9 5 6 ];
A.G(:,:,2) = [0 1 0 0; 0 6 0 0];
A.G(:,:,3) = [0 5 0 0; 0 0 0 0];
N = 10; % random number
idx = find(A.G == 0);
if ~isempty(idx)
A.G(idx(1)) = N;
else
n = size(A.G,3);
A.G(1,1,n+1) = N;
end
disp(A.G);