Capturing numbers from different sized elements in for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (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
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.
참고 항목
카테고리
Help Center 및 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!