MATLAB: How to save logical arrays generated by for loops as matrices

save matrices for loops

Goal: to compare each value from a matrix to an index ranging from 0-4 in increments of 1, saving the results as a matrix.
Please see the sample code below: this produces the answers I want as 5 logical arrays, but the last one is the only one that is saved. I would like to save all 5 logical arrays as either a single matrix or as individual matrices. This is a simplified test run–ultimately, I will use increments of .01 and perform other calculations on each of the 400 matrices produced. Given this, should I save the arrays as a single matrix or as individual matrices for best practices with memory?
test = [1 2 3 4; 2 1 3 4; 3 1 2 4]
inc = zeros(3,4)
for index = 0:1:4
inc = test >= index
end
*Please note: Based on (https://www.mathworks.com/videos/storing-data-in-a-matrix-from-a-loop-97493.html) I have tried writing the last line as:
inc(i) = test >= index
This returns the error "Array indices must be positive integers or logical values."
Thank you in advance!

Best Answer

test = [1 2 3 4; 2 1 3 4; 3 1 2 4];
inc = zeros(size(test,1),size(test,2),5);
for index = 0:1:4
inc(:,:,index+1) = test >= index;
end
inc is now a 3 x 4 x 5 matrix with the third dimension corresponding to the different index values.
You can also skip the looping and do
test = [1 2 3 4; 2 1 3 4; 3 1 2 4];
inc = test >= reshape(0:1:4, 1, 1, []);
Requires R2016b or later.