How to save logical arrays generated by for loops as matrices

11 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Walter Roberson
Walter Roberson el 21 de En. de 2020
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.
  1 comentario
May_the_degrees_of_freedom_be_with_you
Thank you so much for the quick response! Never would have thought to add a third dimension for the index values. Worked perfectly.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by