How to save logical arrays generated by for loops as matrices
18 ビュー (過去 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!