How to save logical arrays generated by for loops as matrices
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
May_the_degrees_of_freedom_be_with_you
am 21 Jan. 2020
Kommentiert: May_the_degrees_of_freedom_be_with_you
am 22 Jan. 2020
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!
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 21 Jan. 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 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!