Capturing numbers from different sized elements in for loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Image Analyst
am 8 Nov. 2015
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 Kommentare
Image Analyst
am 9 Nov. 2015
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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!