How to save logical arrays generated by for loops as matrices
17 次查看(过去 30 天)
显示 更早的评论
May_the_degrees_of_freedom_be_with_you
2020-1-21
评论: May_the_degrees_of_freedom_be_with_you
2020-1-22
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 个评论
采纳的回答
Walter Roberson
2020-1-21
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!