Capturing numbers from different sized elements in for loop
古いコメントを表示
I have a for loop with multiple commands and operators, at the end of the loop I am given important numbers that I would like to store with each iteration of the loop. Each iteration of the loop may contain a different number of values to store. In order to store the values I have used a cell array. This works but I need an easy way to access the numbers within the cell. Below is a similar, though generic, situation to the problem I am facing.
for i=1:10
z=randi(5,1);
store=randi(200,z,1);
all{i}=store;
end
I would like to be able to access the numbers in "all" as doubles or matrices, as opposed to cells or strings. Any help is appreciated in either better methods of collecting within the loop or in transforming the cell array to a double matrix.
回答 (1 件)
Image Analyst
2015 年 11 月 8 日
Don't use "all" as the name of your variable - it's the name of a built in function. Not sure if that is causeing your problem or not but you should not use that name!
Let's say you want the matrix you stored in cell #42 of a cell array called "ca":
theMatrix = ca{42};
Now let's say you want the element at row 3, column 2:
theValue = theMatrix(3, 2);
A structure array is simpler so maybe you'd prefer that over a cell array (which has very high overhead).
5 件のコメント
Bus141
2015 年 11 月 8 日
Note that you should preallocate the cell array, as expanding it on every iterations is very inefficient and can cause memory problems:
Image Analyst
2015 年 11 月 9 日
編集済み: Image Analyst
2015 年 11 月 9 日
I'm not the one who told you to put thousands of different sized matrices into cells - that was your decision. I merely told you how to access them after you stuck them in there. Cell arrays are flexible but very memory inefficient. If you think it's excessive, then don't do it. Use another variable type if you can. Can you use a structure array like I suggested? Or else allocate a 3D array with lateral dimensions that are the largest you ever expect you matrices to be. Do you know the max size they will ever be?
Bus141
2015 年 11 月 9 日
Image Analyst
2015 年 11 月 9 日
Making a 3D array could work, but you might want to have a "rows" array and a "columns" array to keep track of what part of the slice was actually used. Or else initialize unused elements to some flag value, like -99999 so that you can recognize what's been assigned and what's not been assigned at that slice/plane/z-level. This method would take up a LOT less memory and be much faster. Even though it "wastes" some memory, it's not as wasteful as a cell array with it's huge overhead. If it works for you, maybe you could Vote and/or Accept the answer.
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!